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>
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.
The following code demonstrates how to open, read, and detect the end of a file:
#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);}
fopen()
function to open the educative.txt
file. The program stores the file pointer in ptr
and checks for a NULL
value to detect any errors.fgetc()
function displays one character of the file at a time in a while
loop. fgetc()
returns the character indicated by the file pointer and advances the file pointer onto the next character.while
loop terminates once the feof()
function detects the end of the fileFree Resources