C Programming/stdio.h/feof

From Wikibooks, open books for an open world
Jump to navigation Jump to search

feof is a C standard library function declared in the header stdio.h.[1] Its primary purpose is to distinguish between cases where a stream operation has reached the end of a file and cases where the EOF ("end of file") error code has been returned as a generic error indicator, without the end of the file's actually having been reached.

Function prototype[edit | edit source]

The function is declared as follows:

int feof(FILE *fp);

It takes one argument: a pointer to the FILE structure of the stream to check.

Return value[edit | edit source]

The return value of the function is an integer. A nonzero value signifies that the end of the file has been reached; a value of zero signifies that it has not.

Example code[edit | edit source]

 #include <stdio.h>
 
 int main()
 {
     FILE *fp = fopen("file.txt", "r");
     int c;
     c = getc(fp);
     while (c != EOF) {
         /* Echo the file to stdout */
         putchar(c);
         c = getc(fp);
     }
     if (feof(fp))
       puts("End of file was reached.");
     else if (ferror(fp))
       puts("There was an error reading from the stream.");
     else
       /*NOTREACHED*/
       puts("getc() failed in a non-conforming way.");
 
     fclose(fp);
     return 0;
 }

Pitfalls[edit | edit source]

A common misuse of the function is trying to use feof "preemptively". However, this doesn't work correctly, as feof is only set for a descriptor after a reading function has failed.

References[edit | edit source]

  1. ISO/IEC 9899:1999 specification (PDF). p. 305, § 7.19.10.2.

External links[edit | edit source]