QUESTION 11
Why is while (!feof(fp)) usually the wrong read loop?
2 marksAnswer
The end indicator is set only after a read attempts to pass the available input. Test the read operation itself so stale or invalid data is not processed.
QUESTION 11
The end indicator is set only after a read attempts to pass the available input. Test the read operation itself so stale or invalid data is not processed.
QUESTION 12
Stream status functions describe indicators associated with a FILE stream.
while (fgets(buffer, sizeof buffer, fp) != NULL) {
/* process this successfully read text */
}
if (ferror(fp)) {
/* handle a read error */
}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.
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.
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.