首页 > 解决方案 > 如何在 C++ 中追加到文件?

问题描述

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

#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.

标签: c++c++11

解决方案


app改为以模式打开文件myfile.open("example.txt", std::ios_base::app);


推荐阅读