fgetc function-read one character from a file

The fgetc function is a function that reads one character from a file. You can use it by reading the stdio.h header.

#include <stdio.h>
int fgetc (FILE * fp);

Reads one character from the file stream and returns the read character. If the end of the file is reached, EOF is returned.

Sample fgetc function

This is a sample of the fgetc function. fopen function opens the file in read mode, fgetc function reads one character at a time, outputs to standard output, and fclose function.

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

int main (void) {
  
  // Open the file in read mode
  const char * in_file = "input.txt";
  FILE * in_fp = fopen (in_file, "r");
  if (in_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", in_file);
    exit (1);
  }
  
  // Read and output to standard output
  int32_t ch;
  while (ch = fgetc (in_fp)) {
    // If EOF is returned
    if (ch == EOF) {
      // Check if it is the end of the file
      if (feof (in_fp)) {
        break;
      }
    }
    fputc (ch, stdout);
  }
  
  // Close the file with the fclose function
  fclose (in_fp);
}

It is an input file "input.txt".

Hello
World!

This is the output result.

Hello
World!

What if EOF is found in the middle of the file?

If EOF is found in the middle of the file, EOF will be returned. So keep in mind that EOF is not always the true end of file. Use the feof function to verify that it is the end of a real file.

    // If EOF is returned
    if (ch == EOF) {
      // Check if it is the end of the file
      if (feof (in_fp)) {
        break;
      }
    }

What is the difference between the fgetc function and the getc function?

The getc function, like the fget function, reads one character from the file, but is allowed to be implemented as a function macro to improve performance. I am. fgetc is implemented as a function.

As an implementation experience, getc can be implemented as a macro, so it has some side effects. I can't remember for sure, but I've experienced compilation errors in the FreeBSD environment.

If you're happy with read performance and don't want to cause portability issues, you'll want to use the fgetc function.

Associated Information