Contact Learn C
Copy

Program 202:Reading a File and Printing on console

Program 202:
 
#include<stdio.h>
#include<stdlib.h>
 main ()
 {
    FILE *file;
    char c;
    file=fopen("file123.txt","r");
    while(1)
    {
     if(file==NULL)
     {
      printf("File Not Found\n");
      exit(0);
     }
     else
     {
      c=fgetc(file);
      if(c==EOF)
      {
       break;
      }
      printf("%c",c);
     }
    }
    fclose(file);
 }
Explanation:

  1. Declaring file which is FILE pointer and using fopen to open the file with read mode
  2. while(1)
    {
       if(file==NULL)
       {
         printf("File Not Found\n");
         exit(0);
       }
       else
       {
         c=fgetc(file);
         if(c==EOF)
         {
           break;
         }
         printf("%c",c);
       }
     }
    
    
    If file123.txt doesnot exist in the expected location in our local machine/pc then file variable will be null(null means nothing or empty in coding).
  3. If file==null we are printing File not found 
  4. If there is file then while loop continuosly iterate by retrieving character by character using fgetc(file) which will retrieve one character at a time and print that character on console using printf("%c",c); 
  5. If we reach End of the File then fgetc returns EOF to file pointer then we will break our loop and come out of it
  6. Finally, we should close/terminate the file that is opened using fclose 

Output:

Store both text file and program in same folder.Here I named text file as file123.txt










 
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide