Question:
The fstream
class inherits from istream
and ostream
and from other classes. The istream class defines the istream
method, and the ostream
class defines the seekg
seekp
. It's the same with the tellg
and tellp
.
- Do I understand correctly that you need to use the
seekp
andtellp
functions when writing, andseekg
andtellg
when reading from a file? - Should an object of type
std::fstream
, when opened, passopenmode
(std::ios_base::in
orstd::ios_base::out
) when reading and writing, respectively, and use the appropriate functions from theistream
classes whenstd::ios_base::in
and vice versa? - And why, if the
open()
method is called on an object of typestd::fstream
and passed to thestd::ios_base::in
argument, theseekp
method inherited from theostream
class will work correctly, although we indicated that we are going to read from a file, and not output to it? Thanks in advance.
Answer:
The std::fstream
class is an alias for the std::basic_fstream<char, char_traits<char>>
class, which is a subclass of std::basic_iostream<char, char_traits<char>>
, i.e. std::iostream
. And this means that for std::fstream
"father" is std::iostream
, and istream
and ostream
are the parents of the latter, which means that for std::fstream
are only "grandfather" and "grandmother". This is a small correction to your information.
-
That's right, some are used for writing, and other member functions are used for reading.
-
Since an object of type
std::fstream
can (has such an inheritance) both write and read, it does so by default. But if you want it to only write or only read, then you need to set the appropriate mode, but then it makes no sense to use it, and not use another direct descendant ofistream
andostream
, that is,std::ifstream
andstd::ofstream
. -
It follows from all of the above that if you have a std::fstream object , then you have an object with the ability to read and write from / to a file, and therefore you can use it to open a file in any mode. But this does not affect its functionality, as it was able to change the position of the output stream ( seekp), it will be able to, but only the set mode may prevent writing something there