fgetc() function in c – fgetc C Library Function

fgetc() function in c: The function int fgetc(FILE *stream); gets the next character from the input stream from the current position(pointed by the internal file position indicator) and increment the current position indicator. The character is read as unsigned char and type casted to an integer before returning.

Function prototype of fgetc

int fgetc(FILE *stream);
  • stream : A pointer to a FILE object which identifies a stream.

Return value of fgetc

fgetc in c: This function fgetc returns the character read(type casted to an int value) or EOF on end of file or error.

C program using fgetc function

fgetc c: The following program shows the use of fgetc function to read the content of a file. Let file “textFile.txt” contains “fgetc C Standard Library function” string. The content of this file will get printed by the following program.

fgetc C Library Function

#include <stdio.h>
 
int main(){
   FILE *file;
   int c;
   
   file = fopen("textFile.txt", "r");
   if(file == NULL){
      perror("Error: Unable to open a file");
   } else {
       /* Read characters from a file using fgetc */
       while(!feof(file)){
          c = fgetc(file);
          printf("%c", c);
       }
       fclose(file);
   }
    
   return(0);
}

Output

fgetc C Standard Library function