Computer >> Computer tutorials >  >> Programming >> C programming

Explain feof() function in C language with a program


Problem

How the C compiler detect that the file was reached the end for while reading? Explain with a program.

Solution

feof() is a file handling function in C language, which is used to find end of a file.

The logic we used for finding end of file is as follows −

fp = fopen ("number.txt", "r"); //open a file
printf ("file content is\n");
for (i=0;i<=100;i++){
   n = getw(fp); //read each number and store in n
   if(feof(fp)) {//if file pointer reach to end it will break
      printf ("reached end of file");
      break;
   } else {
      printf ("%d\t", n);
   }
}

Exmaple

Following is the C program for the feof() function −

#include<stdio.h>
int main(){
   FILE *fp;
   int i,n;
   fp = fopen ("number.txt", "w");
   for (i=0;i<=100;i= i+10){
      putw(i,fp);
   }
   fclose (fp);
   fp = fopen ("number.txt", "r");
   printf ("file content is\n");
   for (i=0;i<=100;i++){
      n = getw(fp);
      if(feof(fp)){
         printf ("reached end of file");
         break;
      } else {
         printf ("%d\t", n);
      }
   }
   return 0;
}

Output

When the above program is executed, it produces the following result −

file content is
0 10 20 30 40 50 60 70 80 90 100 
reached end of file