【问题标题】:How to append to a file in C++?如何在 C++ 中追加到文件?
【发布时间】:2020-05-19 16:21:15
【问题描述】:

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

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

【问题讨论】:

  • 检查 ofstream open 方法的 mode 参数
  • 一个选项:以追加模式打开文件。
  • 非常感谢@Kryten 和 Johnny

标签: c++ c++11


【解决方案1】:

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

【讨论】:

  • 非常感谢
【解决方案2】:

ofstream 的默认 open mode 是纯 out,它重新创建文件从头开始(如果文件存在,则其内容被截断)。

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

this open reference 中的表格对于理解开放模式及其作用非常有帮助。

【讨论】:

  • 非常感谢
猜你喜欢
  • 2023-03-02
  • 2013-10-17
  • 2013-10-26
  • 2021-08-20
  • 2016-03-18
  • 1970-01-01
  • 2022-01-14
相关资源
最近更新 更多