In C/C++, getc() returns EOF when end of file is reached. getc() also returns EOF when it fails. So, only comparing the value returned by getc() with EOF is not sufficient to check for actual end of file. To solve this problem, C provides feof() which returns non-zero value only if end of file has reached, otherwise it returns 0.
For example, consider the following C program to print contents of file test.txt on screen. In the program, returned value of getc() is compared with EOF first, then there is another check using feof(). By putting this check, we make sure that the program prints “End of file reached” only if end of file is reached. And if getc() returns EOF due to any other reason, then the program prints “Something went wrong”
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- fgets() and gets() in C language
- Basics of File Handling in C
- Read/Write structure to a file in C
- fgetc() and fputc() in C
- scanf() and fscanf() in C - Simple Yet Poweful
- C Program to print numbers from 1 to N without using semicolon?
- Difference between getc(), getchar(), getch() and getche()
- Enumeration (or enum) in C
- C Program to merge contents of two files into a third file
- fopen() for an existing file in write mode
- To find sum of two numbers without using any operator
- How to deallocate memory without using free() in C?
- Memory Layout of C Programs
- fseek() vs rewind() in C
- What is return type of getchar(), fgetc() and getc() ?