C Standard Library

C <stdio.h> - feof() Function



The C <stdio.h> feof() function checks if the end-of-file indicator associated with the file stream is set. It returns a non-zero value if it is set, else returns 0.

The error indicator are generally set by a previous operation on the stream that attempted to read at or past the end-of-file. The indicator gets cleared by calling function like clearerr, rewind, fseek, fsetpos or freopen. Although if the position indicator is not re-positioned by such a call, the next i/o operation is likely to set the indicator again.

Syntax

int feof (FILE * stream);

Parameters

stream Specify a pointer to a FILE object that specifies the stream.

Return Value

Returns non-zero value if the end-of-file indicator associated with the file stream is set, else returns 0.

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 characters to output stream until end-of-file is reached.

#include <stdio.h>
 
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 end-of-file is reached
  if (c != EOF) {
    while(!feof(pFile)) {
      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 <stdio.h> Library