【问题标题】:ios_base::ate and cleaning fileios_base::ate 和清理文件
【发布时间】:2016-11-12 17:23:12
【问题描述】:

请帮忙,代码执行输出而不是

123456

只是

456

为什么在写入之前清除文件?未设置截断

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ofstream a{ "1.txt",ios_base::ate };
    a << "123";
    a.close();
    ofstream b{ "1.txt",ios_base::ate };
    b << "456";
    b.close();
    ifstream c{ "1.txt" };
    string str;
    c >> str;
    cout << str;
    return 0;
}

【问题讨论】:

  • 文件每次都重写
  • 只需阅读您使用的功能的文档。文档非常清楚他们的工作。 -1

标签: c++


【解决方案1】:

您需要在您的第二个编写器中使用app 将内容附加到文件而不是重写它,如下所示:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ofstream a{ "1.txt",ios_base::ate };
    a << "123";
    a.close();
    ofstream b{ "1.txt",ios_base::app }; //notice here is app instead of ate
    b << "456";
    b.close();
    ifstream c{ "1.txt" };
    string str;
    c >> str;
    cout << str;
    return 0;
}

this question

std::ios_base::ate 并不暗示 std::ios_base::app

所以如果你使用ate 并不意味着它会将内容附加到文件中。

【讨论】:

    【解决方案2】:

    您可以找到ios_base:ateios_base:app here 之间的区别

    对于您的代码,您可以这样更改:

    ofstream b {"1.txt", ios_base:app};
    

    【讨论】:

      猜你喜欢
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多