17.7 – Reading unformatted text from the file

by subbu on October 10, 2014

In the previous session, we have learned how to write characters onto the file using fputc(), we have also discoursed EOF macro and feof() function. Now in this session we will learn how to read text from the file.

fgetc() function

It is the function defined within the header file “stdio.h”. By using this, we can read character by character from the file through the file pointer.

fgetc() function in C language

This function accepts the file pointer as argument and returns ASCII value of last fetched (accessed) character from the file. It returns -1 or EOF on reaching the end of file.

Now we will see, How we can read text from unformatted text file step by step

FILE *p;
p=fopen("igate","r");

It opens the file “igate” in read mode and returns the low level details of a file as the file pointer.

ch=fgetc(p);

It reads a single character from the file through the file pointer. If we want to read character by character from the file until the end of file then we need to run a loop until fgetc() returns -1

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

The above loop read character by character from the file and prints onto the console output until the end of file is reached.

Let us put all together as a program

#include<stdio.h>
int main()
{
 FILE *p;
 char ch;
 p=fopen("igate","r"); /* opening the file in read mode */
 while(1)
 {
   ch=fgetc(p);           /* reading character from the file */
   if(ch==-1)              /* checking end of file */
     break;
   printf("%c",ch);      /* printing character on to the console output */
 }
 fclose(p);                 /* closing the file */
 return 0;
}

Execution
The C programming Language
Second Edition
By Brian W. Kernighan and Dennis M. Ritchie

reading text from the file

  1. The file “igate” is opened in read mode (“r”) using fopen() function.
  2. fgetc() fetches character by character through the file pointer.
  3. Characters are printed onto the monitor using printf()
  4. The if(ch==-1) checks for end of file character, breaks if it is reached.
  5. The file is closed after the completion of read operation.

We can write the same program in more professional way

#include<stdio.h>
int main()
{
 FILE *p;
 char fname[20],ch;
 printf("Enter the file name:");
 scanf("%s",fname);
 p=fopen(fname,"r");
 if(p==NULL)
   printf("Sorry..file is not existed..");
 else
 {
   while(1)
   {
    ch=fgetc(p);
    if(ch==-1)
      break;
    printf("%c",ch);
   }
   fclose(p);
 }
 return 0;
}

Execution1:
Enter the file name: hansa
Sorry..file is not existed..

Execution2:
Enter the file name: igate
The C programming Language
Second Edition
By Brian W. Kernighan and Dennis M. Ritchie

Previous post:

Next post: