Error Handling during File Operations
It is possible that an error may occur during I/O operations
on a file. Typical error situations include:
1. Trying
to read beyond the end-of-file mark.
2. Device
overflow means no space in the disk for storing data.
3. Trying
to use a file that has not been opened.
4. Trying
to perform operation on a file, when the file is opened for another type of
operation.
5. Opening
a file with an invalid filename.
6. Try
to read a file with no data in it.
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. Fortunately, we have
two status library functions;
1. feof
2. ferror
that can help us to detect I/O errors in the files.
feof
The feof function
can be used to test for an end of file condition. It takes a FILE pointer as
its only argument and returns a nonzero integer value if all the data from the
specified file has been read, and returns zero otherwise. If fp is a pointer to file that has just
been opened for reading , then the statement
if ( feof ( fp ) )
printf
( “End of data.\n” ) ;
would display the message “End of data.” on reaching the end
of file condition.
ferror
The ferror function
reports the status of the file indicated. It also takes a FILE pointer as its
argument and returns a nonzero integer if an error has been detected up to that
point, during processing. It returns zero otherwise. The statement
if ( ferror ( fp ) ! = 0 )
print
( “An error has occurred.\n” ) ;
would print the error message, if the reading is not
successful.
We know that 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. This facility can be
used to test whether a file has been opened or not. Example:
if ( fp ==
NULL )
printf
(“ File could not be opened.\n”);
Post a Comment