Course contentsShow
← C
Lesson 722 of 1,21910. Input and OutputFree lesson

Why feof inside a loop condition is bad

Why feof inside a loop condition is bad

What you'll learn: Why using feof() to control a loop causes your program to process the last piece of data twice.

The "End of File" Delay

In C, the End-of-File (EOF) flag is like a tripwire. However, the computer doesn't know it has tripped the wire until it actually tries to step over it.

When you use while (!feof(file)), you are asking: "Have I already hit the end?" The problem is that the "end of file" status is only set after a failed read attempt. If you are at the very last character of a file, feof() still returns false because you haven't tried to read past that character yet.

The Off-By-One Ghost

Imagine you are eating a bag of chips. You look in the bag, see it looks empty, but you don't know it's empty until you reach in and pull out nothing but air.

If you use feof() as your loop condition, your code follows this flawed logic:

  1. Check: Is the file at the end? (No).
  2. Read the last piece of data.
  3. Process that data.
  4. Loop back.
  5. Check: Is the file at the end? (Still No! You haven't failed a read yet).
  6. Try to read again. The read fails, but the variables still hold the data from the previous step.
  7. Process the data again. You have now duplicated your last entry.

The Better Way

Instead of asking if the file is over, try to read the data and check if that specific read was successful. In C, input functions like fgets, fscanf, or fgetc return a value that tells you immediately if they succeeded or failed.

// BAD: This will likely print the last line twice
while (!feof(filePtr)) {
    fgets(buffer, 100, filePtr);
    printf("%s", buffer);
}

// GOOD: The loop only runs if the read actually worked
while (fgets(buffer, 100, filePtr) != NULL) {
    printf("%s", buffer);
}

By putting the reading function inside the while condition, you ensure that the body of the loop only executes if there was actually fresh data to handle.

Key takeaway

Don't ask permission to read with feof(); try the read and check if it worked.