How to use foef() in C
The feof() function in C detects the end of a file.
To use the feof() function, the program needs to include the stdio.h header file as shown below:
#include <stdio.h>
Parameters and Return Value
The feof() function only accepts a pointer to a FILE object as the parameter.
feof() returns a single non-zero value of type int if the end of a file is reached, otherwise it returns a 0.
Examples
The following code demonstrates how to open, read, and detect the end of a file:
main.c
educative.txt
#include <stdio.h>int main(){// open a fileFILE *ptr = fopen("educative.txt","r");// check for errorif(ptr == NULL){printf("Error opening file");}// check for end of filewhile(!(feof(ptr))){//get the character and printprintf("%c", fgetc(ptr));}// close the filefclose(ptr);}
Explanation
- The above code employs the
fopen()function to open theeducative.txtfile. The program stores the file pointer inptrand checks for aNULLvalue to detect any errors. - The
fgetc()function displays one character of the file at a time in awhileloop.fgetc()returns the character indicated by the file pointer and advances the file pointer onto the next character. - The
whileloop terminates once thefeof()function detects the end of the file
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved