ios_base :: ate和清理文件

时间:2016-07-10 19:01:35

标签: c++

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

123456

456

为什么在写文件之前清除文件? Trunc未设置

#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;
}

2 个答案:

答案 0 :(得分:0)

您需要在第二个编写器中使用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,则并不意味着它会将内容附加到文件中。

答案 1 :(得分:0)

您可以在ios_base:ateios_base:app here

之间找到不同的内容

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

ofstream b {"1.txt", ios_base:app};
相关问题