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

标签 c++ iostream

以下代码是在 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::appios::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]: [..] If mode 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/

相关文章:

c++ - 将 boost::visitor 与 unique_ptr 的 boost::variant 结合使用

c++ - 如何在 C++ 中创建字符数组数组? (仅使用 iostream)

c++ - 如何将输出设置为中间?

c++ - extract>> 运算符在 C++ 中究竟是如何工作的

c++ - Visual Studio 不显示符号表?

c++ - 如何查看 CXX 和 CXXFLAG 的值

c++ - 如何使用 ATL 创建 VB6 集合对象

c++ - 使用 std::visit 示例的堆栈溢出

c++ - 如果导入 iostream 为什么要使用命名空间

c++ - std::cout 的十六进制 0x00