为什么ofstream("log.txt",ios :: app | ios :: trunc); 总是失败?

xml*_*lmx 8 c++ iostream

以下代码是使用Windows 7 x64上的VC++ Nov 2012 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?
    }
}
Run Code Online (Sandbox Code Playgroud)

cppreference.com网站并未说ios::app不能与之合并ios::trunc.

什么是确切的语义ios::appios::trunc

Lig*_*ica 21

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"            |
+-----------------------------------+-------------------+
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,你的标志组合在表中找到.

[C++11: 27.9.1.4/2]: [..]如果mode不是表格中显示的某些标志组合,则打开失败.

那些是语义.

[C++11: 27.9.1.7/2][C++11: 27.9.1.11/2]告诉我们模式从流对象传递到缓冲区对象.


Mat*_*ias 6

  • app(= append):在每次输出操作之前将流的位置指示器设置为流的末尾
  • trunc(= truncate)丢弃任何当前内容,假设打开时长度为零.

正如您所看到的,将两者放在一起是没有意义的.

  • 请保留评论以提出澄清问题并回答。关于特定主题的扩展讨论应保留在 [Chat](http://chat.stackoverflow.com) 中。此外,涉及谩骂的讨论也将被删除。 (2认同)