For performing file IO in C++ we use the ofstream, ifstream and fstream classes.
- ofstream: Stream class to write on files
- ifstream: Stream class to read from files
- fstream: Stream class to both read and write from/to files
The process of associating a file with a stream object is called “opening the file”.
When opening a file we can specify the mode in which the file is to be opened.
My query is related to the ios::out and ios:in modes.
When I create an ofstream object and open the file with ios::in mode, I am able to
write into the file but only if its created already(with ios::out mode file is also created if it doesn’t already exist).
But when I create ifstream object and open the file with ios::out mode, I am able to read from the file.
My question is why these modes (ios::in/ios::out) are supplied by the language when the type of the stream(ifstream/ofstream) itself specifies as to which type of operation(input/output) is being performed ?
Also why this ambiguous usage(ofstream with ios::in and ifstream with ios::out) works in one case and fails(though only if file is not already present) in another ?
The
ofstream,ifstreamandfstreamclasses are high level interfaces for the underlyingfilebuf, which one can access through therdbuf()member function of the stream.When you open an
ofstreamwith some modemode, it opens the underlying stream buffer withmode | ios_base::out. Analogouslyifstreamusesmode | ios_base::in.fstreampasses themodeparameter verbatim to the underlying stream buffer.What the above implies is that the following code opens the file with exactly the same open flags:
After these lines you can do exactly the same things with
f.rdbuf(),g.rdbuf()andh.rdbuf(), and all the three act as if you opened the file with the C callfopen("a.txt", "r+"), which gives you read/write access, does not truncate the file, and fails if the file does not exist.So, why do we have three different classes? As previously stated, these are high level classes providing a high-level interface over the lower-level stream buffer. The idea is that
ifstreamhas member functions for input (likeread()),ofstreamhas member functions for output (likewrite()) whilefstreamhas both. For example you cannot do this:But this works, because, although
gis anifstream, we opened it withios_base::out: