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

Distinguishing EOF from errors with ferror

Distinguishing EOF from errors with ferror

What you'll learn: How to determine if a file operation stopped because it reached the end of the data or because a technical failure occurred.

The Ambiguity of EOF

In C, many input functions like fgetc() or fscanf() return a special constant called EOF when they can no longer read data. However, there is a catch: these functions return EOF for two very different reasons.

Think of it like a waiter bringing you water. If they stop pouring, it could be because the pitcher is empty (End of File), or it could be because they tripped and dropped the pitcher (a Runtime Error). In both cases, the water stops flowing, but the reason matters. If you just assume the pitcher is empty, you might ignore a broken glass on the floor.

Using ferror() to Clear the Air

To solve this ambiguity, C provides two "diagnostic" functions: feof() and ferror().

  • feof(file_pointer) returns true only if the "End of File" indicator has been set.
  • ferror(file_pointer) returns true only if an actual read/write error occurred (like a disk failure or a lost network connection).

When your reading loop terminates, you should immediately check ferror() to ensure everything went as planned.

Concrete Example

Here is how you handle the distinction in a standard reading loop:

#include <stdio.h>

int main() {
    FILE *file = fopen("data.txt", "r");
    if (file == NULL) return 1;

    int ch;
    // Attempt to read until fgetc returns EOF
    while ((ch = fgetc(file)) != EOF) {
        putchar(ch);
    }

    // The loop ended. Why?
    if (ferror(file)) {
        printf("\nResult: A critical error occurred while reading.\n");
    } else if (feof(file)) {
        printf("\nResult: Reached the end of the file successfully.\n");
    }

    fclose(file);
    return 0;
}

Why This Matters

If you only check for feof(), your program might enter an infinite loop or silently fail if a hardware error occurs. By checking ferror(), you make your code "robust." You are telling the computer: "Stop if the file is over, but alert me if something actually broke."

Remember that EOF is just a signal that the stream has stopped; ferror() is the tool that tells you if that stop was an accident.

Key takeaway

Always use ferror() after a file loop ends to confirm the data stream stopped due to reaching the end, not due to a hardware or system failure.