What is std::fstream ?
std::fstream is a bi-directional file stream class. That is, it provides an interface for input and output of files. It is usually used when the user needs to read and write to the same external sequence.
When creating a bi-directional file stream (unlike std::ofstream or std::ifstream ), the openmodes ios_base::in and ios_base::out parameters are set by default. This means that it is:
std::fstream f("test.txt", std::ios_base::in | std::ios_base::out);
coincides with
std::fstream f("test.txt");
You can specify both parameters if they also need to add some weak openmodes, such as trunc , ate , app or binary . The open ios_base::trunc necessary if you intend to create a new file for bi-directional I / O, because ios_base::in openmode disables the creation of a new file.
Bidirectional I / O
Bidirectional I / O is the use of a bi-directional stream for input and output. In IOStreams, standard streams maintain their character sequences in a buffer, where it serves as the source or receiver for the data. For output streams, there is a "put" area (a buffer that contains characters for output). Similarly, there is a βgetβ area for input streams.
In the case of std::fstream (a class for input and output), it contains a unified file buffer representing the get and put regions, respectively. The position indicator, which marks the current position in the file, depends on the input and output operations. Thus, in order to properly perform I / O in a bidirectional stream, you must follow certain rules:
- When you read after writing, or vice versa, the stream must be reinstalled back.
- If the input operation gets to the end of the file, writing right after that is fine.
This only applies to std::fstream . The above rules are not needed for std::stringstream .
I hope they answer your questions. If you have more, you can just ask in the comments.