Pages

To Read a File in C

Friday 28 June 2013
C program to read a file: This program reads a file entered by the user, and displays the contents of the screen, a file structure again fopen function to open a file pointer. FILE is a predefined structure stdio.h. If the file has been opened fopen as a pointer back to the file and if it is not able to open a file so that it returns NULL. fgetc function read a character from the file and close the file fclose function. Opening a file means that we can bring run from the hard disk into memory the file. The operations file must exist in the directory where the executable of this code available basis.

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

int main()
{
   char ch;
   char file_name[25];
   FILE *fp;

   printf("Enter the name of file you wish to see\n");
   gets(file_name);

   fp = fopen(file_name,"r");                                    // read mode
   if( fp == NULL )
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }
   printf("The contents of %s file are :\n", file_name);
   while( ( ch = fgetc(fp) ) != EOF )
      printf("%c",ch);
   fclose(fp);
   return 0;
}

No comments:

Post a Comment