What is fgetc() in C?

fgetc() reads a single character from a file at the location indicated by the file pointer. After reading the character from the file, fgetc() increments the file pointer by one location. Below is the declaration of the fgetc() function:

int fgetc (FILE * stream);

Return value

The fgetc() function returns the ASCII value of the character that is read from the file if the read operation is successful. If there is an error when reading from the file, EOFEnd-of-File is returned.

Parameter of the fgetc() function

  • stream: Pointer to the file from which the character is read.

Code

Consider the code snippet below, which uses fgetc() to read the content of a file character by character:

main.c
fgetcExample.txt
#include <stdio.h>
int main() {
FILE * fPointer;
char character;
fPointer = fopen ("fgetcExample.txt", "r");//opening file
while( !feof(fPointer) )//checking EOF
{
character = fgetc(fPointer);
if(character!=EOF)//if EOF returned
{
printf("%c",character);
}
}
fclose(fPointer);
return 0;
}

The fgetc() function is used in line 12, which reads the content of the file fgetcExample.txt character by character and prints the content of the file on the screen.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved