如何在C++中附加到文件?

How to append to a file in C++?

本文关键字:文件 C++      更新时间:2023-10-16

我想通过几个单独的调用将一些数据打印到文件中。我注意到写入的默认行为会覆盖以前写入的数据。

#include <iostream>
#include <fstream>
using namespace std;
void hehehaha (){
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.n";
myfile.close();
}
int main () {
for(int i=0; i <3 ; i++){
hehehaha();}
return 0;
}

这段代码只写一行Writing this to a file.但我想要的是以下内容:

Writing this to a file.
Writing this to a file.
Writing this to a file.

app模式打开文件,而不是myfile.open("example.txt", std::ios_base::app);

ofstream的默认打开模式是普通out,它从头开始重新创建文件(如果文件存在,则其内容将被截断(。

要附加到文件,您需要使用app模式,或添加标志ate

open参考中的表对于了解开放模式及其功能非常有帮助。