Friday, November 4, 2011

Detecting Errors in Reading/Writing in C programming language

Not at all times when we perform a read or write operation on a file are we successful in doing so. Naturally there must be a provision to test whether our attempt to read/write was successful or not.
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
This means we can precede the system error message with any message of our choice. In our program we have just displayed the filename in place of the error message.

No comments:

Post a Comment