1. Summary
  2. Files
  3. Support
  4. Report Spam
  5. Create account
  6. Log in

Feof

From cpwiki

(Difference between revisions)
Jump to: navigation, search
(Controlling file reading loops: Replaced the example)
m (2 revisions)
 

Current revision as of 11:21, 4 November 2008

This page is about feof, the C function which tests a file stream for end-of-file status, which also applies to the C++ equivalent, eof.

int feof (FILE * stream);

Controlling file reading loops

While it is seemingly logical to keep reading a file until you reach the end of the file, the feof function does not lend itself to that ideally. It can only return true after EOF was set for the stream by another input function, such as fgets. Meaning that there is a lag between your loop's end and your function calls, which can lead to an undesirable result.

The problem rears itself consistently if one were to read an empty file:


#include <stdio.h>

int main ()
{
    FILE * fin = fopen("empty.txt", "r");

    if (fin != NULL) {
        char input[] = "garbage";

        while (!feof(fin)) {
            fgets(input, sizeof input, fin);
            fputs(input, stdout);
        }
        fclose(fin);
    }

    return 0;
}

/** my output: 
garbage**/


Provided that the file is truly empty, prompt loop termination would have prevented "garbage" from being printed, or indeed any other program instruction from being followed. Fortunately, the interface for FILEs (defined in <stdio.h>) have correctly designed input functions which will return a unique value if reading from the stream had failed. Incorporating the reading step as the loop condition itself will produce the ideal outcome.

Fixing the example is left as an exercise for the reader.

Personal tools