C getc() Function Tutorial

In this section, we will learn what the getc() function is and how it works in C.

C getc() Function

A call to the `getc-function` is used to get one character at a time from a file.

Note: each call to this function returns only one character of the target file.

Also, any time we call the function, it will advance to the next character of the target file until it reaches to the end of the file, which in that case the return value is an especial character called EOF. This character means the file ended and there’s no content to read anymore.

The prototype of the function exists in the `stdio.h` header file and so we need to include the header file in order to work with the function.

C getc() Function Syntax:

Here’s the prototype of the `getc` function:

int getc(FILE *stream)

C getc() Function Parameters

As you can see, this function only takes one argument and that is a pointer to the FILE-structure of the target file.

Note: we get this pointer from the call to the `fopen` function.

C getc() Function Return Value

As mentioned before, the returned value of the function is a character stored in the target file.

Note: Any time we call the function; it will advance to the next character exist in the file we set as its argument.

Example: using getc() function in C

#include <stdio.h>
#include <stdlib.h>
int main() {

    //Call the the fopen function in order to open the file in read mode.
    FILE *file = fopen("G:/fileOne.txt","r+");
    //if there was a problem on opening the file, exit the program.
    if (file == NULL){
        exit(EXIT_FAILURE);
    }

    char c;
    while ((c = getc(file))!=EOF){
        printf("%c",c);
    }

    fclose(file);


    printf("\ndone\n");
    return 0;
}

Output:

Hello there

Done
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies