c++ – A few questions about std::fstream


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 .

  1. Do I understand correctly that you need to use the seekp and tellp functions when writing, and seekg and tellg when reading from a file?
  2. Should an object of type std::fstream , when opened, pass openmode ( std::ios_base::in or std::ios_base::out ) when reading and writing, respectively, and use the appropriate functions from the istream classes when std::ios_base::in and vice versa?
  3. And why, if the open() method is called on an object of type std::fstream and passed to the std::ios_base::in argument, the seekp method inherited from the ostream class will work correctly, although we indicated that we are going to read from a file, and not output to it? Thanks in advance.


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.

  1. That's right, some are used for writing, and other member functions are used for reading.

  2. 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 of istream and ostream , that is, std::ifstream and std::ofstream .

  3. 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

Scroll to Top