as

Thursday 13 November 2014

Reading a File in C

Below program shows how to read the file character by character.

#include<stdio.h>             

#include<stdlib.h>

void main()
{
   // here declare a file in pointer.
   FILE *filep;                           

   char ch;
     
    //fopen function is used to open a text file
    //Please note that mode of the file is r.
     
    filep =fopen("c:\\abc.txt","r"); 
     
    if (!filep)
    {
      printf ("File does not exist\n");
      getchar();
      exit(0);
    }
     
    printf("The data in file is :- \n");

     //fgetc function is used to read the character from file.
     //fgets function is used to read the string from a file.
     
     while((ch=fgetc(filep))!=EOF)  

     {
      printf("%c",ch);
     }
     
      fclose(filep);   
           
      // Here close the text file.
           
  getchar();
}    


Below program shows how to read file line by line.

#include<stdio.h>             
#include<stdlib.h>

void main()
{
   // here declare a file in pointer.
   FILE *filep;
   char *str = malloc(255);                           

   char ch;
     
    //fopen function is used to open a text file
    //Please note that mode of the file is r.
     
    filep =fopen("abc.txt","r"); 
     
    if (!filep)
    {
      printf ("File does not exist\n");
      getchar();
      exit(0);
    }
     
    printf("The data in file is :- \n");

     //fgetc function is used to read the character from file.
     //fgets function is used to read the string from a file.
     
     while(fgets(str,255,filep))    
     
     {
      printf("%s",str);
     }
     
      fclose(filep);
}







No comments:

Post a Comment

Leave your valuable feedback. Your thoughts do matter to us.

Sponsored Links

Popular Posts

Comments

ShareThis