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?

  1. A.

    To read the next character from the file stream

  2. B.

    To determine whether the end-of-file indicator for the file stream has been set

  3. C.

    To close the file after all characters are read

  4. D.

    To move the file pointer to the beginning of the file

  5. 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

  1. The loop while ((ch = fgetc(file)) != EOF) keeps reading one character at a time and printing it. fgetc returns the character as an int, or the macro EOF when no more characters can be read.

  2. The loop exits when fgetc returns EOF. That return value alone is ambiguous: it can mean a genuine end-of-file OR a read error.

  3. 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 rewind or fseek(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.

Explore the full course: Ibps So It Mains

Loading lesson…