clearerr - Linux


Overview

clearerr clears the end-of-file indicator for a stream. This allows subsequent read operations to continue reading data from the stream.

Syntax

clearerr(FILE *stream);
  • stream: The stream to clear the end-of-file indicator for.

Options/Flags

None.

Examples

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp;
    char buf[1024];

    if ((fp = fopen("myfile.txt", "r")) == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    // Read until the end of the file is reached
    while (fgets(buf, sizeof(buf), fp) != NULL) {
        // Process the line
    }

    // Clear the end-of-file indicator to continue reading
    clearerr(fp);

    // Continue reading from the file
    while (fgets(buf, sizeof(buf), fp) != NULL) {
        // Process the line
    }

    fclose(fp);

    return 0;
}

Common Issues

Error reading from a stream:

If an error occurs while reading from a stream, the end-of-file indicator may be set. This will cause subsequent read operations to fail. To resolve this issue, use clearerr to clear the end-of-file indicator before continuing to read.

Integration

feof:

clearerr can be used in conjunction with feof to determine if the end of a stream has been reached.

fscanf:

clearerr can be used to reset the input stream for fscanf.

Related Commands

  • feof – checks if the end of a stream has been reached
  • fseek – moves the file pointer to a specific position in a stream
  • rewind – moves the file pointer to the beginning of a stream