[英]How to append to a file in C++?
I want to print some data to a file with a few separate calls.我想通过几个单独的调用将一些数据打印到文件中。 I noticed that the default behaviour for a write overwrites the previously written data.我注意到写入的默认行为会覆盖以前写入的数据。
#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;
}
this code writes only one line Writing this to a file.
此代码仅写入一行Writing this to a file.
but what I want is the following:但我想要的是以下内容:
Writing this to a file.
Writing this to a file.
Writing this to a file.
The default open mode for ofstream
is plain out
, which recreates the file from scratch (if the file exists, its contents is truncated). ofstream
的默认打开模式是 plain out
,它从头开始重新创建文件(如果文件存在,则其内容被截断)。
To append to a file you need to use the app
mode, or add the flag ate
.到 append 到一个你需要使用app
模式的文件,或者添加标志ate
。
The table in this open
reference is quite helpful to understand the open-modes and what they do.这个open
参考中的表格对于理解开放模式及其作用非常有帮助。
Open the file in app
mode instead myfile.open("example.txt", std::ios_base::app);
改为以app
模式打开文件myfile.open("example.txt", std::ios_base::app);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.