In this section, we will learn what the feof() function is and how it works in C.
C feof() Function
When reading the content of a file, we often times want to stop the operation when the end of that file reached.
One of the ways to find out if the end of a file is reached or not is via the call to the `feof()` function.
Note: we need to include the `stdio.h` header file in order to work with this function because the prototype of the function is in this file.
C feof() Function Syntax:
Here’s the prototype of the function:
int feof(FILE *stream)
C feof() Function Parameters
This function takes one argument and that is the address of the memory space allocated to the FILE-structure of the target file.
C feof() Function Return Value
The function returns a non-zero value when the end of the file reached and zero if the file is not at its end.
Example: using feof() function in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *file = fopen("G:/fileOne.txt","a+");
if (file == NULL){
printf("Could not open the file");
exit(EXIT_FAILURE);
}
char c;
while (1){
c = getc(file);
if (feof(file)){
break;
}
printf("%c",c);
}
fclose(file);
printf("\nDone\n");
return 0;
}
Output:
Hello, my name is John Doe Done