C++ ios_base::ate和清理文件
请帮助,代码执行输出,而不是C++ ios_base::ate和清理文件,c++,C++,请帮助,代码执行输出,而不是 123456 只是 为什么文件在写入之前被清除?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.cl
123456
只是
为什么文件在写入之前被清除?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;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
int main()
{
流a{“1.txt”,ios_base::ate};
str;
cout您需要在第二个writer中使用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;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
int main()
{
流a{“1.txt”,ios_base::ate};
str;
您可以找到ios\u base:ate
和ios\u base:app
对于您的代码,您可以如下更改:
ofstream b {"1.txt", ios_base:app};
每次都会重写该文件。请阅读您使用的函数的文档。文档非常清楚它们的作用。-1
ofstream b {"1.txt", ios_base:app};