Per [ofstream.cons]/itemdecl:2 http://eel.is/c++draft/ofstream.cons#itemdecl:2:
explicit basic_ofstream(const char* s,
ios_base::openmode mode = ios_base::out);
因此,默认模式为ofstream
is out
。然而,每[选项卡:filebuf.open.modes] http://eel.is/c++draft/filebuf.members#tab:filebuf.open.modes, out
and out | trunc
两者都对应于 stdio 等效项"w"
,所以它们是等价的。每C11 7.21.5.3 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf#%5B%7B%22num%22%3A695%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C-27%2C816%2Cnull%5D:
w
:截断到零长度或创建用于写入的文本文件
因此,默认模式是正确的out
,并且说默认模式相当于out | trunc
。这是有保证的行为。
另一方面,每[fstream.cons]/itemdecl:2 http://eel.is/c++draft/fstream.cons#itemdecl:2:
explicit basic_fstream(
const char* s,
ios_base::openmode mode = ios_base::in | ios_base::out);
因此,默认模式为fstream
is in | out
. Per [选项卡:filebuf.open.modes] http://eel.is/c++draft/filebuf.members#tab:filebuf.open.modes, in | out
对应于"r+"
, while in | out | trunc
对应于"w+"
,所以它们不等价。每C11 7.21.5.3 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf#%5B%7B%22num%22%3A695%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C-27%2C816%2Cnull%5D:
r+
:打开文本文件进行更新(读取和写入)
w+
:截断到零长度或创建文本文件以进行更新
所以,fstream
除非您指定,否则不会截断trunc
。
请注意,如果所需的文件不存在,r+
将失败而不是创建文件。相比之下,w
and w+
在这种情况下,两者都会创建一个新文件。
(也可以看看:fopen https://en.cppreference.com/w/c/io/fopen在 cppreference 上)