I/O Status. McGraw-Hill The Complete Reference Fourth Edition
Iklan
Iklan
C h a p t e r 2 1 : C + + F i l e I / O
561
Obtaining the Current File Position
You can determine the current position of each file pointer by using these functions: pos_type tellg( ); pos_type tellp( );
Here, pos_type is a type defined by ios that is capable of holding the largest value that either function can return. You can use the values returned by tellg( ) and tellp( ) as arguments to the following forms of seekg( ) and seekp( ), respectively.
istream &seekg(pos_type pos); ostream &seekp(pos_type pos);
These functions allow you to save the current file location, perform other file operations, and then reset the file location to its previously saved location.
I/O Status
The C++ I/O system maintains status information about the outcome of each I/O operation. The current state of the I/O system is held in an object of type iostate, which is an enumeration defined by ios that includes the following members.
Name Meaning ios::goodbit No error bits set ios::eofbit 1 when end-of-file is encountered; 0 otherwise ios::failbit ios::badbit
1 when a (possibly) nonfatal I/O error has occurred;
0 otherwise
1 when a fatal I/O error has occurred; 0 otherwise
There are two ways in which you can obtain I/O status information. First, you can call the rdstate( ) function. It has this prototype: iostate rdstate( );
It returns the current status of the error flags. As you can probably guess from looking at the preceding list of flags, rdstate( ) returns goodbit when no error has occurred.
Otherwise, an error flag is turned on.
562
C + + : T h e C o m p l e t e R e f e r e n c e
The following program illustrates rdstate( ). It displays the contents of a text file.
If an error occurs, the program reports it, using checkstatus( ).
#include <iostream>
#include <fstream> using namespace std; void checkstatus(ifstream &in); int main(int argc, char *argv[])
{ if(argc!=2) { cout << "Usage: Display <filename>\n"; return 1;
} ifstream in(argv[1]); if(!in) { cout << "Cannot open input file.\n"; return 1;
} char c; while(in.get(c)) { if(in) cout << c; checkstatus(in);
}
} checkstatus(in); // check final status in.close(); return 0; void checkstatus(ifstream &in)
{ ios::iostate i; i = in.rdstate(); if(i & ios::eofbit) cout << "EOF encountered\n";
Unduh
Iklan