On the previous section we opened an input stream, and we opened an output stream.
We could have used fstream, an unbounded file stream allowing both reading and writing.
fstream fstrm;
fstrm.open(s, mode);
Modes, for this and the I/O versions, partially:
in, out, app, ate, trunc, binary
Multiple modes can be set. They are part of fstream::
app: Always write at the end.
ate: On opening go the end.
trunc: Wipes out existing content.
binary: Doesn’t have the text conversion layer, you read/write in binary.
There are constraints on these flags. Some examples:
out is for fstream or ofstream.
trunc can only be set if out is.
app and trunc are mutually exclusive.
Don’t assume a file stream has been opened successfully.
Incorrect file name:
inFile.open("names.txl");
Incorrect file opening mode:
ifstream inFile;
inFile.open("names.txt", ios::trunc);
Not enough room on the hard drive.
Hardware failure.
Always check the status of a stream after open.
So the file seemed to open okay but being pessimistic, what goes wrong next.
The program may not have data to read as it hits the end of file.
The data may be invalid: ... an alphabetic character instead of a digit character; a control character instead of an alphabetic one; etc.
The data may not be physically accessed from the disk due to its damage or network failure.