- So far, we have assumed that all stream operations have been successful; this is a dangerous assumption
- There are many potential errors when dealing with files
- Input files may not exist; output files may be read-only; disks can become full; users may not have read/write privileges with certain files
- We have seen 3 functions associated with streams: open(), close(), and eof().
- There are many others, some of which are used to detect errors; fail() is useful for error detection
ifstream myIn;
myIn.open("datafile.in", ios::in);
// test to see if there was an error; if there was
// an error, it is not safe to proceed
if ( myIn.fail() )
cout << "Unable to open input file" << endl;
else
{
while ( !myIn.eof() )
{
// process data in file
}
myIn.close(); // close the file here
}