C programming stdio.h function - int fgetc(FILE *stream)

The fgetc() function is defined in the <stdio.h> header file of the C standard library, and it is used to read a single character from a file pointed to by the stream parameter. The function has the following signature:

int fgetc(FILE *stream);
Sourc‮:e‬www.theitroad.com

The function reads the next character from the file pointed to by stream and returns it as an unsigned char cast to an int, or EOF if the end-of-file or an error occurs. EOF is a constant defined in <stdio.h> that represents the end-of-file indicator.

The file position indicator associated with the stream is incremented by one and the state of the stream is updated.

Here is an example that reads characters from a file using fgetc() until the end of file is reached:

#include <stdio.h>

int main() {
   FILE *fp;
   int c;

   fp = fopen("file.txt", "r");
   if (fp == NULL) {
      perror("Error opening file");
      return 1;
   }

   while ((c = fgetc(fp)) != EOF) {
      putchar(c);
   }

   fclose(fp);
   return 0;
}

This program reads each character from the file "file.txt" and prints it to the console until the end of the file is reached.