File Handling In C 4

Error Handling during I/O operations

It is possible that an error may occur during I/O operation on the file. Typical error situations include:

  • Trying to read beyond the end of the file mark.
  • Device overflow
  • Trying to use a file that has not been opened.
  • Trying to perform an operation on a file, when the file is opened for another operation
  • Opening a file with an invalid filename.
  • Attempting to write to a write-protected file.

If we fail to check such read and write errors , a program may behave abnormally when an error occurs. An unchecked error may result in a premature termination of the program or incorrect output.

If we fail to check such read and write errors , a program may behave abnormally when an error occurs. An unchecked error may result in a premature termination of the program or incorrect output.

Function used for error checking

Whenever a file is opened using fopen() function , a file pointer is returned. If the file cannot be opened for some reason ,then the function returns a NULL pointer. So it is always important to check whether the file has been successfully opened or not before using it.

FILE *fp;
fp=fopen(“hello”,”r”);
if(fp==NULL)
{
   printf(“unable to open the file\n”);
   return;/break;
}

feof() :

This function helps us to check an end of file condition. It takes the file pointer as an argument , returns a nonzero integer if all the data of the specified file has been read otherwise zero is returned.

if(feof(fp))
{
   printf(“End of file\n”);
   return;/ break;
}
message “End of file” will be displayed when end of file is reached.

ferror():

This function helps us to check whether the file processing has been successful or not. It takes the file pointer as an argument and returns a non zero value if an error has been detected.

if(ferror(fp)!=0)
{
   printf(“An error has occurred\n”);
   return;/break;
}

Number Of Visitors

0270465