fgetc() Function in C

The syntax of the fgetc() functon is:

Syntax: int fgetc(FILE *fp);

This function is complementary to fputc() function. It reads a single character from the file and increments the file position pointer. To use this function file must be opened in read mode. On success, it returns the ASCII value of the character but you can also assign the result to a variable of type char. On failure or end of file, it returns EOF or -1.

Just as fputc() this function uses buffer memory too. So instead of reading a single character from the file one by one, a whole block of characters from the file is read into the buffer. The characters are then handed over one at a time to the function fgetc(), until the buffer is empty. If there are still some characters left to read in the file then again a block of characters is read into the buffer.

The following program demonstrates how to use fgetc() function.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int ch;
    FILE *fp;
    fp = fopen("myfile.txt", "r");

    if(fp == NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }

    printf("Reading contents of myfile.txt: \n\n");

    while( (ch=fgetc(fp)) != EOF )
    {
        printf("%c", ch, ch);
    }

    fclose(fp);
    return 0;
}

Expected Output:

Reading contents of myfile.txt:

Testing fputc() function

How it works ?

In line 6, a variable ch of type int is declared.

In line 7, a structure pointer variable fp of type struct FILE is declared.

In line 8, fopen() function is called with two arguments namely "myfile.txt" and "r" . On success, it returns a pointer to file "myfile.txt" and opens the file "myfile.txt" in read-only mode. On failure or end of file, it returns NULL.

In line 10, if statement is used to test the value of fp. If it is NULL, printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.

In line 16, printf() statement prints "Reading contents of myfile.txt: \n\n" to the console.

In lines 18-21, a while loop is used to read characters one by one from the file and prints it to the console using printf() statement (you can also use putchar() function). The parentheses around ch = fgetc(fp) is necessary because the precedence of != operator is greater than that of = operator.

In line 23, fclose() function is used to close the file.