C Programming Tutorial
Computer Tutorial

Reading from a File



Reading from a File

Once the file has been opened for reading using fopen( ), as we have seen, the file’s contents are brought into buffer (partly or wholly) and a pointer is set up that points to the first character in the buffer. This pointer is one of the elements of the structure to which fp is pointing
To read the file’s contents from memory there exists a function called fgetc( ). This has been used in our program as,
ch = fgetc ( fp ) ;
fgetc( ) reads the character from the current pointer position, advances the pointer position so that it now points to the next character, and returns the character that is read, which we collected in the variable ch. Note that once the file has been opened, we no longer refer to the file by its name, but through the file pointer fp.
While reading from the file, when fgetc( ) encounters this special character, instead of returning the character that it has read, it returns the macro EOF. The EOF macro has been defined in the file “stdio.h”. In place of the function fgetc( ) we could have as well used the macro getc( ) with the same effect.

Note

Some compiler vendors (like Microsoft, Borland, etc.) provide their own keywords apart from the ones mentioned above. These include extended keywords like near, far, asm, etc.