Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

I thought that it's guaranteed by the standard that std::ios_base::out also truncates the file (and all of the STL implementations which I know do this). Am I wrong and should explicitly notify that I want to truncate the file?

like image 507
FrozenHeart Avatar asked Aug 04 '13 07:08

FrozenHeart


3 Answers

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

The point of std::ios_base::trunc is when std::ios_base::in and std::ios_base::out are used the same time.

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

Maybe a table would be more obvious:

binary  in  out  trunc | stdio equivalent
-----------------------+-----------------
         +   +         |      "r+"
         +   +     +   |      "w+"
  +      +   +         |      "r+b"
  +      +   +     +   |      "w+b"
like image 100
timothyqiu Avatar answered Oct 21 '22 07:10

timothyqiu


To replace a file's content rather than extending the file, it must be opened in

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

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

For bidirectional file streams, however, trunc must always be explicitly specified.

To extend an output file, flag std::ios_base::ate | std::ios_base::app is used.

Here, the file content is retained because the trunc flag is not set, and the initial file position is at the file's end.

However, additionally trunc flag can be set, and the file content is discarded and the output is done at the end of an empty file.

like image 43
P0W Avatar answered Oct 21 '22 08:10

P0W


It is redundant - in other words, it makes no difference if you have it or not.

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

like image 1
Mats Petersson Avatar answered Oct 21 '22 06:10

Mats Petersson