C++ Standard Library C++ STL Library

C++ <cstdio> - EOF constant



The C++ <cstdio> EOF is a macro constant definition of type int that expands into a constant expression (generally -1).

It is used as the value returned by several functions to indicate either the End-of-File has been reached, or to indicate some other failure conditions.

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 getc() function is not EOF, it starts reading characters the file one by one and writes the character to output stream.

#include <cstdio>
 
int main (){
  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  
  //first character in the file
  int c = getc(pFile);
  
  //if first character is not EOF, reads and writes
  //characters from the file until EOF is reached
  while (c != EOF) {
    putchar(c);
    c = getc(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