File Input/Output - Reading from a text file(Output)

File I/O: reading a text file

If you want to read a file you have to open it for reading in the read (r) mode. Then the fgets library functions can be used to read the contents of the file. (It is also possible to make use of the library function fscanf. But you have to be sure that the file is perfectly formatted or fscanf will not handle it correctly). Let’s take a look at an example:

 #include<stdio.h>

 int main()
 {
      FILE *ptr_file;
      char buf[1000];

      ptr_file =fopen("input.txt","r");
      if (!ptr_file)
          return 1;

      while (fgets(buf,1000, ptr_file)!=NULL)
          printf("%s",buf);

  fclose(ptr_file);
      return 0;
 }

Note:The printf statement does not have the new-line (\n) in the format string. This is not necessary because the library function fgets adds the \n to the end of each line it reads.
A file “input.txt” is opened for reading using the function fopen en the mode read (r). The library function fgets will read each line (with a maximum of 1000 characters per line.) If the end-of-file (EOF) is reached the fgets function will return a NULL value. Each line will be printed on stdout (normally your screen) until the EOF is reached. The file is then closed and the program will end.


Spread the word! By sharing this Post!

Pageviews This Week