Using std::fstream
one can declare objects of both the types ifstream
and ofstream
. The only difference is that, with fstream
we need to provide in
, out
, app
as a parameter which may not always require for other two.
Is there anything special about ifstream,ofstream
which cannot be accomplished with fstream
or just a coding convenience ?
ifstream is input file stream which allows you to read the contents of a file. ofstream is output file stream which allows you to write contents to a file. fstream allows both reading from and writing to files by default.
The ifstream Class. An ifstream is an input file stream, i.e. a stream of data used for reading input from a file. Because an ifstream IS an istream, anything you can do to an istream you can also do the same way to an ifstream.
The class ofstream is used for output to a file. Both of these classes are defined in the standard C++ library header fstream . Here are the steps required for handling a file for either input or output: Create an instance of ifstream or ofstream .
What is std::fstream ? std::fstream is a bidirectional file stream class. That is, it provides an interface for both input and output for files. It is commonly used when a user needs to read from and write to the same external sequence.
If anything, fstream
is the one that's just a convenience. In particular, what you have is basically:
namespace std {
class ifstream { /* ... */ };
class ofstream { /* ... */ };
class fstream : public ifstream, public ofstream { /* ... */ };
}
[obviously skipping over a lot of irrelevant details].
In short, the fstream
provides all of the input capabilities of an ifstream
and all the output capabilities of a ofstream
by deriving from both ifstream
and ofstream
. Without ifstream
and ofstream
, an fstream
(at least in anything resembling its current form) couldn't exist at all.
It's a bit like asking why we'd want const
when you can read and write from variables anyway. It allows compile-time checking, an invaluable feature for reducing bugs. It's also more self-documenting, as when looking at a declaration without the constructor call you can see whether it's an input, output or both: the parameters you mention can often only be seen in the implementation file which may not be to hand. Also, each type of stream may have a few differences in the data members they need - potentially using the minimally-functional class matching your actual needs could save memory, time initialising or checking those other variables etc..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With