What is the purpose of using std :: ios_base :: trunc flag with std :: ios_base :: out

What is the purpose of using the std::ios_base::trunc with std::ios_base::out ? I have seen this in many examples.

I thought it was guaranteed by the standard that std::ios_base::out also truncates the file (and all the STL implementations that I know do this). Am I mistaken and should explicitly notify that I want to trim the file?

+4
source share
3 answers

Yes, std::ios_base::out equivalent to "w" in fopen .

The point of std::ios_base::trunc is that at the same time std::ios_base::in and std::ios_base::out .

  • in | out in | out equivalent to "r+"
  • in | out | trunc in | out | trunc equivalent to "w+"
  • binary | in | out binary | in | out equivalent to "rb+"
  • binary | in | out | trunc binary | in | out | trunc equivalent to "wb+"

Maybe the table will be more obvious:

 binary in out trunc | stdio equivalent -----------------------+----------------- + + | "r+" + + + | "w+" + + + | "r+b" + + + + | "w+b" 
+3
source

To replace the contents of a file, rather than expand it, you need to open it in

std::ios_base::out | std::ios_base::trunc

For output file streams, open mode is equivalent to out|trunc , that is, the trunc flag can be omitted.

However, for bidirectional file streams, trunc must be explicitly specified.

To expand the output file, use the flag std::ios_base::ate | std::ios_base::app std::ios_base::ate | std::ios_base::app .

Here the contents of the file are saved, since the trunc flag trunc not set, and the initial position of the file is at the end of the file.

However, in addition, the trunc flag can be set, and the contents of the file will be discarded, and the output will be executed at the end of the empty file.

+3
source

It's redundant - in other words, it doesn't matter if you have it or not.

Obviously, in some combinations, such as std::ios_base::out | std::ios_base::in std::ios_base::out | std::ios_base::in , this would NOT be redundant.

+1
source

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


All Articles