feof() function in C is another major function in file handling function in c programming.

What is feof() function in C?

While you are reading data from the file using any file function (fgets, fgetc etc) it only gets the data from where the current File pointer is pointing it is not sufficient as the file has a huge amount of data. So when you want to access all the data present in file you need to check whether you have accessed all data and reached to end of the file. For this feof() function is used.
feof() function in C: – This function is used to check the end of file for a given file.

feof() function syntax: –
int feof(FILE *fp);

In the above syntax, we can see that function feof accepts only one parameter which is a pointer to the File.
feof() function returns non zero value of end of file reached otherwise it returns zero.

Program to demonstrate feof() function in C

#include<stdio.h>

int main () {

FILE *fp;

char c;

printf ("opening the file in read mode");

fp = fopen("technical.txt","r"); //opening file in read mode

if(fp == NULL) {

printf("Can't open file");

exit(0);

}

printf ("\nreading from file ----");

while(1) {

c = fgetc(fp);. //reading character from file

if( feof(fp) ) { //checking end of file

printf ("\n\nwe reached end of file ");

break ;

}

printf("%c", c);

}
printf ("\nClose the file");
fclose(fp);

return(0);

}

Program description: –
In the above program, we are reading the content of the file until the end of the file reached.

1. First, we open the file in reading mode.
Let us assume technical.txt file exists in the current directory with content (content:- Learn c programming at Defineloop site)
2. We write while to print character in the file in while we write if function if (feof(fp)) which checks the end of file reached if file reached the end then if satisfies and we break the execution otherwise we print data that we got from a file using fgetc function.
3. We can see all the data from the file printed on the screen.

Output: –
feof() function in C

Write A Comment