Files - 3 Function in File Handling

Files - 3 File I/O Functions in File Handling

In the previous post we studies about writing and reading a character from file. During the read operation if file on which read operation being performed if does not exist the program gets crashed. Hence after writing a fopen() function always we have to check for file existence. If file does not exists fopen() returns NULL. Based on this we can take further action like printing a proper message indicating the error or ask for the correct file name.

/* Example for reading characters from file  */
# include < stdio.h >
main()
{
FILE *fp;
char c, fname[30];

fp=fopen("Sample.txt","r");

if( fp == NULL )
   {
      printf( "\n File does not exist ");
      printf( "\n Enter the correct file name ");
      gets ( fname );
      fp = fopen( fname, "r" );

      if ( fp == NULL )
         {
             printf( "\n Error in opening a file " );
             exit(1);
         }
   }
else
while(!feof(fp))
{
c=getc(fp);
printf("%c",c); /*putchar(c);*/
}
fclose(fp);
}
In the above program initially  variables are declared. Using fopen() a file by name sample.txt is opened. If the file is opened correctly without any errors then continue with while loop to repeat fetching and printing a characters from file. If the file does not exist fopen() returns NULL and it will be assigned to fp. Using if statement it is checked whether fp is having NULL if so a proper error message "File does not exist " will be printed and asked to input correct file name using gets() function and it will be stored in a string variable
fname. fopen() is used once again to open the  file. If again error, then by giving message the control of execution will come out from program using exit() function

Comments

  1. There is an error in the while loop for printing the contents of the file.
    while(!feof(fp))
    {
    c=getc(fp);
    printf("%c",c); /*putchar(c);*/
    }
    Here, a char is read and printed and then only the condition checks for EOF error. This will cause the EOF char returned by getc to be printed on the output.
    To prevent this from happening, checking for feof must be before printf. Also, the return value of getc could be made the loop condition, as it avoids unnecessary calls to feof.

    ReplyDelete
    Replies
    1. Thank Arjun for indicating error kindly check the following code whether it solves above problem waiting for ur reply
      do
      {
      c=getc(fp);
      if(c!=EOF)
      printf("%c",c); /*putchar(c);*/
      } while(c!=EOF);

      Delete
    2. Yes. It does. But the following code is more optimal:

      while(1)
      {
      c=getc(fp);
      if(c==EOF)
      break;
      printf("%c",c); /*putchar(c);*/
      }

      Delete

Post a Comment