簡體   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