Consider the following C code snippet: #include <stdio.h> int main() { FILE…
2023
Consider the following C code snippet:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
int ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
if (feof(file)) {
printf("\nEnd of file reached.\n");
}
fclose(file);
return 0;
}
What is the purpose of the feof(file) function call in this program?
- A.
To read the next character from the file stream
- B.
To determine whether the end-of-file indicator for the file stream has been set
- C.
To close the file after all characters are read
- D.
To move the file pointer to the beginning of the file
- E.
To open the file in read mode
Attempted by 16 students.
Show answer & explanation
Correct answer: B
Concept
In C's standard I/O library, each open stream keeps two status flags: an end-of-file (EOF) indicator and an error indicator. A read function does NOT set the EOF indicator merely by returning the EOF value; the indicator is set only after an attempt to read past the last byte actually fails. feof is a pure test: it returns non-zero if the EOF indicator for that stream is currently set, and zero otherwise. It inspects a flag; it neither reads data nor moves the file position.
Applying it to this program
The loop
while ((ch = fgetc(file)) != EOF)keeps reading one character at a time and printing it.fgetcreturns the character as an int, or the macroEOFwhen no more characters can be read.The loop exits when
fgetcreturnsEOF. That return value alone is ambiguous: it can mean a genuine end-of-file OR a read error.To disambiguate, the program calls
feof(file). If it returns non-zero, the EOF indicator is set, so the stream really reached its end, and the program prints the end-of-file message.
Cross-check / contrast
Reading the next character is the job of
fgetc/getc, which return the byte and advance the position; a status-test function returns no data.Closing the stream is done by
fclose, which flushes and releases the stream.Repositioning to the start is done by
rewindorfseek(file, 0, SEEK_SET); a status test never moves the position.Opening in read mode is done by
fopen("...", "r"), which happens before any reading.
Therefore feof(file) exists to report whether the end-of-file indicator for the stream has been set — a status query used here to confirm the loop ended because the file was fully read.