C Library - feof() function



The C library int feof(FILE *stream) function tests the end-of-file indicator for the given stream.This function is part of the standard input/output library (stdio.h) and is important for managing file reading operations in a controlled manner.

Syntax

Following is the C library syntax of the feof() function −

int feof(FILE *stream);

Parameters

This function accepts only a single parameter −

  • FILE *stream: This is a pointer to a FILE object that identifies the stream to be checked.

Return Value

The feof function returns a non-zero value if the end-of-file indicator associated with the stream is set. Otherwise, it returns zero.

Example 1: Basic File Reading Until EOF

This program reads characters from example file and prints them until feof indicates the end of the file.

Below is the illustration of C library feof() function.

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "r");
   if (file == NULL) {
       perror("Failed to open file");
       return 1;
   }

   while (!feof(file)) {
       char c = fgetc(file);
       if (feof(file)) break;
       putchar(c);
   }

   fclose(file);
   return 0;
}

Output

The above code prints the content of example.txt to the console as result.−

Welcome to tutorials point

Example 2: Reading Lines Until EOF with fgets

Here the program reads lines from example3.txt using fgets and prints them until feof confirms that the end of the file has been reached.

#include <stdio.h>

int main() {
   FILE *file = fopen("example3.txt", "r");
   if (file == NULL) {
       perror("Failed to open file");
       return 1;
   }

   char buffer[256];
   while (fgets(buffer, sizeof(buffer), file) != NULL) {
       printf("%s", buffer);
   }

   if (feof(file)) {
       printf("End of file reached.\n");
   }

   fclose(file);
   return 0;
}

Output

After execution of above code,the content of example3.txt will be printed line by line, followed by the message:

End of file reached.
Advertisements