According to this C++ reference: http://www.cplusplus.com/reference/fstream/ofstream/ofstream/, the default open mode for std::ofstream
is ios_base::out
and it mentions no implict other modes. Therefore I would expect that if I overwrite a large file with a small file, the "exceeding" part of the large file should stay untouched and only the first part of the file should be replaced by the new, shorter data.
On the other hand, the Apache C++ Standard Library User's Guide (http://stdcxx.apache.org/doc/stdlibug/30-3.html) states in the note to paragraph 30.3.1.2: "For output file streams the open mode out is equivalent to out|trunc, that is, you can omit the trunc flag. For bidirectional file streams, however, trunc must always be explicitly specified."
I have tried this code:
#include <fstream>
int main()
{
std::ofstream aFileStream("a.out", std::ios_base::out);
aFileStream << "Hello world!";
aFileStream.close();
std::ofstream aFileStream2("a.out", std::ios::out);
aFileStream2 << "Bye!";
aFileStream2.close();
}
Both, with g++ 8.1 on Windows and g++ 6.3 on Linux, the Apache documentation seems to be right. The large file is truncated, nothing remains after writing the shorter string with the second file stream.
Why is it like that? Is cplusplus.com wrong? Or on what does the behaviour depent?