C++ Standard Library C++ STL Library

C++ <cstdio> - fgetc() Function



The C++ <cstdio> fgetc() function returns the character currently pointed by the internal file position indicator of the specified stream and advances the position indicator to the next character.

If the stream is at the end-of-file when called, the function returns EOF and sets the end-of-file indicator for the stream feof(). If a read error occurs, the function returns EOF and sets the error indicator for the stream ferror().

fgetc() and getc() are equivalent, except that getc() may be implemented as a macro in some libraries.

Syntax

int fgetc ( FILE * stream );

Parameters

stream Specify a pointer to a FILE object that specifies an input stream.

Return Value

  • On success, the character read is returned.
  • If the failure has been caused due to end-of-file condition, returns EOF and sets the end-of-file indicator for the stream feof().
  • If a read error occurs, the function returns EOF and sets the error indicator for the stream ferror().

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, file is opened using fopen() function. If the return value of calling fgetc() function is not EOF, it starts reading characters the file one by one and writes the characters to output stream.

#include <stdio.h>
 
int main (){
  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  
  //first character in the file
  int c = fgetc(pFile);
  
  //if first character is not EOF, reads and writes
  //characters from the file until EOF is not reached
  while (c != EOF) {
    putchar(c);
    c = fgetc(pFile);
  }
  
  //close the file
  fclose(pFile);
  return 0;
}

The output of the above code will be:

This is a test file.
It contains dummy content.

❮ C++ <cstdio> Library

5