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

Clearing file error indicators with clearerr

Clearing file error indicators with clearerr

What you'll learn: How to reset a file's error and end-of-file flags so you can resume operations after an issue occurs.

The Sticky "Error" Flag

Imagine you are reading a book, and you reach a page that is stuck shut. You realize you can't read any further, so you mark that page with a red "Error" sticker. Even if someone later comes by and unpricks the page for you, that red sticker remains on the book. If you try to read it again, you see the sticker and immediately stop, thinking, "Oh, this book is broken."

In C, file streams (FILE*) work the same way. When a function like fread or fgetc hits the end of a file or encounters a hardware glitch, the stream sets an internal flag (a "sticky note") indicating an error or EOF (End Of File). Once these flags are set, almost all future attempts to read or write to that stream will fail immediately, even if the underlying problem is gone.

Enter clearerr

The clearerr function is your way of peeling those sticky notes off. It resets both the error indicator and the end-of-file indicator for a specific stream.

You typically use this when you’ve handled a recoverable error. For example, if a network drive was temporarily disconnected and then reconnected, your program might want to try reading the file again. Without clearerr, the stream would still report an error state, and your retry would fail instantly.

Seeing it in Action

Here is how you might reset a stream after hitting the end of a file, allowing you to "rewind" and start fresh:

#include <stdio.h>

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

    // Read until the end of the file
    while (fgetc(file) != EOF);

    // At this point, feof(file) is true. 
    // Any further reads will fail.

    if (feof(file)) {
        printf("Reached end of file. Clearing indicators...\n");
        
        // Reset the EOF and error flags
        clearerr(file);
        
        // Move back to the start to read again
        rewind(file);
    }

    // Now we can read again because the flags were cleared
    int c = fgetc(file);
    if (c != EOF) {
        printf("Successfully read first char again: %c\n", c);
    }

    fclose(file);
    return 0;
}

When to use it

You don't need clearerr for every tiny mistake, but it is essential when you want to "forgive" the stream. If you detect an error using ferror, handle the problem (like asking the user to plug a USB drive back in), you must call clearerr before the stream will let you work with it again.

Key takeaway

The clearerr function resets a stream's error and EOF flags, effectively giving the file pointer a "clean slate" to resume operations.