What Is an EOF in the C Language?
- Understanding how the EOF symbol works means understanding how file input works. Typically, the programmer loads the file into the program through a file pointer. Using the "stdio.h" libraries, the programmer can use a file pointer to reference a file in memory, and then either read from or write to the file. The following example shows how to declare and use a file pointer:
#include "stdio.h"
int main(){
FILE * fp; //file pointer
fp = fopen("c:\\file.txt", "r") //opens "file.txt" as read-only, and uses fp to reference it - The programmer then reads from the file. She can do this using the "fgetc()" function, which will read from the file one character at a time. The "fgetc()" function returns an integer value, which can be changed to a character by the programmer to print to the screen or for whatever manipulation is required:
int ch = fgetc(fp);
printf("%c", (char)ch); - When the "fgetc()" function reads a character, it moves an internal file pointer forward one space. This means that as a file is read by the function, the file always remains ready for another read. How the internal file pointer works is not important to the programmer or the function. What is important is that as the file pointer moves forward during successful readings, it will eventually hit the end of the file; it will not, for example, continue reading the file beyond the file's size.
- When the file pointer passes the final character, the "fgetc()" function will return a negative integer value tied to a macro called "EOF." A macro is a redefinition of a value into a more readable form. The programmer can check for this value by using the "EOF" macro. If the function returns the value, the programmer can halt reading of the file and avoid any errors, as in this example:
int c;
while ((c = fgetc(fp)) != EOF) //when c contains the EOF value, the loop will stop reading
{
putchar (c);
}
Reading a File
Reading From a File
Internal File Pointers
The End of File
Source...