How does std :: fstream work with which it should work both internally and externally?

I was just starting to wonder - how is std::fstream actually open with both std::ios::in and std::ios::out , which should work? What to do? Write something (for example) to an empty file, then read ... what? Just written value? Where will the file "pointer" / "cursor" be? Perhaps the answers are already there, but I just could not find it.

+6
source share
1 answer

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.

+5
source

Source: https://habr.com/ru/post/943917/


All Articles