Upload
dinesh-bhawnani
View
85
Download
1
Embed Size (px)
DESCRIPTION
Error Handling During File Operations
Citation preview
Error Handling During File Manipulations
In the real time environment, many users access different files without any predefined access pattern. The following are the different situations that can arise while manipulating a file;1. Attempting to open a non-existent file in read mode.2. Trying to open a read-only marked file in write mode. 3. Trying to open a file with invalid name.4. Attempting to read beyond the end of file.5. Sufficient disk space is not available while writing to a file.6. Attempting to manipulate an unopened file.7. Stream object created bat not connected to a file.8. Media (disk) errors reading/writing a file.
Such conditions must be detected while manipulating files and appropriate action should be taken to achieve consistent access to files.
Every stream (ifstream, ofstream, and fstream) has a state associated with it. Errors and nonstandard conditions are handled by setting and testing this stale appropriately. The stream status variable and information recorded by its bits is shown in Figure below.
Fig. State Variable Format
The ios class supports several functions to access the status recorded in the data member io_state. These functions and the meaning of their return values are shown in Table below.
Table : Error handling functions and their return values
Function Meaning of return valueeof ( ) TRUE, (non-zero) if EOF encountered while reading
FALSE, (zero) otherwisefail ( ) TRUE, if read or write operation has failed;
FALSE, otherwisebad ( ) TRUE, invalid operation is attempted or any unrecoverable errors
FALSE, otherwise however, it can be recoveredgood ( ) TRUE, if operation is successful i.e., all the above are functions that return false,
if file.good ( ) is true, everything is fine and can proceed for further processingrdstate ( ) returns the status – state data member of the class iosclear ( ) clear error states and further operations can be attempted
The following examples illustrate the mechanism for checking errors during file operations:
1. Opening a non-existent file in read mode : ifstream inflie("myfile.dat");if(!infile){
// file does not exist}
2. Open fail: opening read-only marked fileofstream outfile(“myfile.dat" ); if{ Unfile J // or if( infile.badf) )
( // file already exist and marked as read only ) 3. Detectingendoffile while* •infile.eoff) ) ft processes until end-of-file is reached { If process file } 4. Read fail infile.read(...}; iff infile.badO ) ! // file cannot be processed further }
-5. Invalid filename infile,openf \ -, if{ Unfile ) t // invalid file name ) 6. Processing unopened file infile.readf..); // read file iff infile.failf) ) { // file is not opened - !