Detecting Errors in Reading and Writing in C

Detecting Errors

The standard library function ferror( ) reports any error that might have occurred during a read/write operation on a file. It returns a zero if the read/write is successful and a non-zero value in case of a failure. The following program illustrates the usage of ferror( ).

#include "stdio.h" 
main( ) 
{ 
 FILE *fp ; 
 char ch ; 
 fp = fopen ( "TRIAL", "w" ) ; 
 while ( !feof ( fp ) ) 
 { 
 ch = fgetc ( fp ) ; 
 if ( ferror( ) ) 
 { 

printf ( "Error in reading file" ) ; 
 break ; 
 } 
 else 
 printf ( "%c", ch ) ; 
 } 
 fclose ( fp ) ; 
}

In this program the fgetc( ) function would obviously fail first time around since the file has been opened for writing, whereas fgetc( ) is attempting to read from the file. The moment the error occurs ferror( ) returns a non-zero value and the if block gets executed. Instead of printing the error message using printf( ) we can use the standard library function perror( ) which prints the error message specified by the compiler. Thus in the above program the perror( ) function can be used as shown below.

if ( ferror( ) ) 
{ 
 perror ( "TRIAL" ) ; 
 break ; 
} 

Note that when the error occurs the error message that is displayed is:

TRIAL: Permission denied

Leave a Comment