ifstream
and ofstream
is for input and output in file, and fstream
can do task of both them but not inherited from either of ifstream
and ofstream
, is this code repetition or something else?
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.
File streams are a lot like cin and cout File streams come in two flavors also: the class ifstream (input file stream) inherits from istream, and the class ofstream (output file stream) inherits from ostream.
The I/O system of C++ contains a set of classes which define the file handling methods. These include ifstream, ofstream and fstream classes. These classes area derived from fstream and from the corresponding iostream class.
An fstream is an iostream which writes to and reads from a file. So: every fstream is an iostream but not every iostream is an fstream.
You'd have to ask the author, Bjarne Stroustrup, for a definitive answer. In his original paper on iostreams published in USENIX Proceedings of 1985, he seems to put a lot of emphasis on efficiency:
Inline expanded functions are used for the basic operations (like "put a character into a buffer"), so the basic overhead tend to be one function call per simple object (integer, string, etc.) written (or read) plus one function call per buffer overflow.
So that could be the reason.
I guess you could extract common file I/O functionality into a mixin, but that would require virtual
inheritance in order to allow for the diamond inheritance, which would add an extra indirection when accessing the underlying basic_filebuf
.
In addition, as a file read/write mode normally cannot be changed once the file is opened, being able to cast fstream
to ifstream
or ofstream
would create inconsistencies as you could get a writable ifstream
or a readable ofstream
.
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