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?
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"
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With