Error
Handling
It is possible that error may occur during I/O operations on a file. Some situations
which generates error such as:
1.
When Trying to read beyond
the end –of – file mark.
2.
When device overflow.
3.
When trying to use file
that has not been opened.
4.
When trying to perform an
operations on a file , when the file is open for another type of operations.
5.
When opening a file with an
invalid name.
6.
When attempting to write to a write – protected file.
If such errors may not be checked
, program may return abnormal output and errors occurred. An unchecked
error may result in premature termination of program or incorrect output. Error
handling function in file handling provide prevention of such errors.feof() and
ferror() functions help to detect errors in file.
feof()
This function is used for testing end of file condition.
Syntax:
feof(File-ptr);
As shown in above syntax File-ptr is the pointer to the file structure.
It returns true (1) integer value if all the data read from the
specified file, otherwise it returns false (0).
Ex,
if(feof(fp))
printf(“\n
End of file reached”);
Here , if file pointer reached at end of file then it return true (1)
ferror()
This function can be used to test file is opened properly or not . This
function reports the status of the file.
Syntax:
ferror(File-ptr);
As shown in above syntax File-ptr is the pointer to the file structure.
It returns true (1) integer value if an error has been detected during
process, otherwise it returns false (0).
Ex,
if(ferror(fp) !=0)
printf(“\n
Error has occured”);
Here , if reading is not possible then it prints the error message.
NULL
Pointer
When open any file fopen() function is used. This function returned file
pointer. If the file can not be opened for some reason , then the function
returns a NULL pointer.
This facility can be used to test whether a file has been properly
opened or not.
Ex,
if((fopen(“data.txt”,”r”))==NULL)
printf(“\n File could
not open”);
Posted By : Ruchita Pandya
No comments:
Post a Comment