Skip to study material
← Question index

QUESTION 12

Explain feof, ferror and clearerr and correct end-of-file testing.

5 marks

Answer in brief

Stream status functions describe indicators associated with a FILE stream.

Functions

  1. feof(fp) reports whether the end-of-file indicator is set.
  2. ferror(fp) reports whether the error indicator is set.
  3. clearerr(fp) clears both indicators; it does not restore missing data or fix an underlying device failure.

Correct loop

while (fgets(buffer, sizeof buffer, fp) != NULL) {
    /* process this successfully read text */
}
if (ferror(fp)) {
    /* handle a read error */
}

Why the operation is tested

Before an attempted read beyond the available data, feof may still be false. A loop controlled only by feof can therefore execute again after the useful input has ended and accidentally process old buffer contents. The successful-read condition prevents that extra processing.

EOF is a return indicator

fgetc returns int and uses EOF to signal its end/error result. EOF is not a special ordinary character appended to every file. Once the read loop ends, ferror can distinguish an error from normal completion for the example’s purpose.

Position interaction

A successful fseek clears the EOF indicator. rewind resets position and clears indicators, but it has no returned success value; use suitable checked positioning when failure must be reported. Status checks are fixed-size operations in the interface; scanning the file still requires work proportional to the bytes read.