繁体   English   中英

如何将 append 到 C++ 中的文件?

[英]How to append to a file in 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.

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

到 append 到一个你需要使用app模式的文件,或者添加标志ate

这个open参考中的表格对于理解开放模式及其作用非常有帮助。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM