![]() |
VOOZH | about |
Handling file input in C often involves EOF and functions like getc() and feof().
In C, EOF is a constant macro defined in the <stdio.h> header file that is used to denote the end of the file in C file handling. It is used by various file reading functions such as fread(), gets(), getc(), etc.
The value of EOF is implementation-defined, but generally is -1.
The getc() function is used to read a single character from the given file stream. It is implemented as a macro in <stdio.h> header file.
Syntax
getc(fptr);
Parameters: fptr: It is a pointer to a file stream to read the data from.
Return Value
The feof() function is used to check whether the file pointer to a stream is pointing to the end of the file or not. It returns a non-zero value if the end is reached, otherwise, it returns 0.
Syntax
feof(fptr);
Parameters: fptr: Pointer to a file stream to read the data from.
Return Value
getc() returns the End of File (EOF) when the end of the 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 the actual end of the file. To solve this problem, C provides feof(). Example:
End of File or Unable to Read
In the above program, the getc() function should be unable to read as the file is opened in the write mode only. But it still returns EOF because of which it becomes difficult to find the source of error. Here, the feof() function can be specifically used to check for End of File.
Unable to Read