C Library - fgetc() function



The C library fgetc() function gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. It is commonly used for reading characters from files.

Syntax

Following is the C library syntax of fgetc() function −

int fgetc(FILE *stream);

Parameter

stream : A pointer to a FILE object that identifies the input stream. This stream is usually obtained by opening a file using the fopen function.

Return Value

The function returns the character read from the stream as an unsigned char cast to an int.If the end-of-file is encountered or an error occurs, the function returns EOF, which is a macro typically defined as -1. To distinguish between an actual character and an EOF return, one should use the feof or ferror functions to check if the end of the file or an error has occurred.

Example 1

This example reads and prints the first character of "example1.txt". If the file is empty or an error occurs.

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "r");
   if (file == NULL) {
      perror("Error opening file");
      return 1;
   }

   int ch = fgetc(file);
   if (ch != EOF) {
      printf("The first character is: %c\n", ch);
   } else {
      printf("No characters to read or error reading file\n");
   }
   fclose(file);
   return 0;
}

Output

The above code produces following result −

The first character is: H

Example 2: Counting Characters in a File

This example counts and prints the total number of characters in "example3.txt".

#include <stdio.h>

int main() {
   FILE *file = fopen("example3.txt", "r");
   if (file == NULL) {
      perror("Error opening file");
      return 1;
   }

   int ch;
   int count = 0;
   while ((ch = fgetc(file)) != EOF) {
      count++;
   }

   printf("Total number of characters: %d\n", count);

   fclose(file);
   return 0;
}

Output

After execution of above code, we get the following result

Total number of characters: 57
Advertisements