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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- What is return type of getchar(), fgetc() and getc() ?
- Difference between getc(), getchar(), getch() and getche()
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- What are the differences between bitwise and logical AND operators in C/C++?
- Difference and Similarities between PHP and C
- INT_MAX and INT_MIN in C/C++ and Applications
- Lex program to take input from file and remove multiple spaces, lines and tabs
- Similarities and Differences between Ruby and C language
- Code Optimization Technique (logical AND and logical OR)
- Getting System and Process Information Using C Programming and Shell in Linux
- Change/add only one character and print '*' exactly 20 times
- Comma in C and C++
- Return values of printf() and scanf() in C/C++
- Difference Between malloc() and calloc() with Examples
- How does "void *" differ in C and C++?
- exit(), abort() and assert()
- What are the operators that can be and cannot be overloaded in C++?
- Write one line functions for strcat() and strcmp()
- Data type of character constants in C and C++
- Can we use function on left side of an expression in C and C++?