以下代码是在 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?
}
}
The cppreference.com website并没有说 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]:
[..] Ifmode
is not some combination of flags shown in the table then the open fails.
这些是语义。
† [C++11: 27.9.1.7/2]
& [C++11: 27.9.1.11/2]
向我们展示了模式从流对象传递到缓冲区对象。
关于c++ - 为什么 ofstream ("log.txt", ios::app|ios::trunc);总是失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15084007/