Reading from a File in C

Once the file has been opened for reading using fopen(), as we have seen, the file’s contents are brought into buffer 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 the memory, there exists a function called fgetc(). This has been used in our program as:

ch = fgetc(fp);

fgetc() performs the following operations:

  1. Reads the characters from the current pointer position
  2. Advances the pointer position so that it now points to the next character
  3. Returns the character that is read, which we collected in the variable ch

While reading a file, when the function fgetc() reached end of the file, it returns a special character whose ASCII value is 26 which signifies the end of file.

When fgetc() encounters this special character, it does not return this special character. Instead it returns a macro EOF. The macro EOF has been defined in the file “stdio.h”.

Hence we use the below logic to determine the end of the file while reading from the file.

while(1)
{
   ch = fgetc(fp);
   if (ch == EOF)
      break;
   printf("%c", ch);
}

The logic reads as follows:
When the character “ch” read from the file is equal to the macro “EOF”, break the while loop execution. That is, stop reading from the file as we have encountered end of file.

You may also like...

2 Responses

  1. zezaomachado says:

    I may want some help.
    How to copy a binfile to an exact range of address in another binfile? Let’s say:
    copy FileA.bin to the address 315 75BF until 315 791F inside of the FileB.bin.

  2. murtaza says:

    how to add the numbers entered in a file?

Leave a Reply

Your email address will not be published. Required fields are marked *

FREE C Cheatsheet - Speed Up Your C Programming.

FREE C Cheatsheet - Speed Up Your C Programming.

Download a 7-page free cheat sheet for easy and quick access to C Concepts, Snippets, and Syntax.

Thank you! Check you inbox and access your cheat-sheet