以下代码是在Windows 7 x64上使用VC++2012年11月CTP编译的。
#include <fstream>
using namespace std;
int main()
{
ofstream fout("log.txt", ios::app|ios::trunc);
if (!fout)
{
cout << "An error occurred!" << endl; // Always go here! Why?
}
}
cppreference.com网站没有说ios::app
不能与ios::trunc
组合。
ios::app
和ios::trunc
的确切语义是什么?
这些标志传递到的filebuf
构造函数†具有基于C++11:中表132中定义的那些标志的行为
+-----------------------------------+-------------------+
| ios_base flag combination | stdio equivalent |
| binary in out trunc app | |
+-----------------------------------+-------------------+
| + | "w" |
| + + | "a" |
| + | "a" |
| + + | "w" |
| + | "r" |
| + + | "r+" |
| + + + | "w+" |
| + + + | "a+" |
| + + | "a+" |
+-----------------------------------+-------------------+
| + + | "wb" |
| + + + | "ab" |
| + + | "ab" |
| + + + | "wb" |
| + + | "rb" |
| + + + | "r+b" |
| + + + + | "w+b" |
| + + + + | "a+b" |
| + + + | "a+b" |
+-----------------------------------+-------------------+
正如您所看到的,您的标志组合是,而不是该表中的。
[C++11: 27.9.1.4/2]:
[..]如果mode
不是表中显示的某些标志组合,则打开失败。
这些就是语义。
&dagger[C++11: 27.9.1.7/2]
&[C++11: 27.9.1.11/2]
向我们展示了模式是从流对象传递到缓冲区对象的
- app(=append(:在每次输出操作之前,将流的位置指示器设置到流的末尾
- trunca(=truncate(任何当前内容都将被丢弃,假设打开时长度为零
正如你所看到的,把两者放在一起是没有意义的。