HOWTO · C++

如何在 C++ 中將文字追加到檔案

本文介紹瞭如何用 C++ 將文字追加到檔案中的方法

本頁內容

處理檔案是程式設計中的一項常見任務,C++ 提供了強大的檔案操作工具。一項常見的操作是向現有檔案追加文字。

本文探討了實現這一目標的多種方法,並提供程式碼示例和說明,幫助您徹底理解這一過程。

使用 ofstream 和 std::ios::app 旗標將文字追加到檔案中

在 C++ 中,std::ofstream 類別是標準樣板函式庫 (STL) 的一部分,用於向檔案寫入資料。當您想要建立、開啟、寫入文字檔案或向其追加資料時,它是一個極好的選擇。

此外,std::ios::app 旗標是 std::ofstream 的一個重要組成部分。使用它時,它會指示資料流以追加模式開啟檔案,這意味著您寫入資料流的任何資料都將被新增到現有檔案內容的末尾。

如果檔案不存在,則會建立該檔案。

現在,要使用帶 std::ios::app 旗標的 std::ofstream 在 C++ 中將文字追加到檔案,可以按照以下步驟操作:

  • 包含必要的標頭檔:
    #include <fstream>
    #include <iostream>
    
  • 使用 std::ofstream 物件以追加模式 (std::ios::app) 開啟檔案。
  • 使用 << 運算子將要追加的文字寫入檔案。
  • 完成後關閉檔案。

下面是一個示例:

#include <fstream>
#include <iostream>

int main() {
  // File path
  std::string filePath = "example.txt";

  // Open the file in append mode
  std::ofstream outputFile(filePath, std::ios::app);

  if (!outputFile) {
    std::cerr << "Failed to open the file for appending." << std::endl;
    return 1;
  }

  // Text to append to the file
  std::string textToAppend = "This is some appended text.";

  // Append the text to the file
  outputFile << textToAppend << std::endl;

  // Close the file
  outputFile.close();

  std::cout << "Text appended to the file successfully." << std::endl;

  return 0;
}

在本例中,我們首先使用 std::ios::app 以追加模式開啟了檔案 example.txt。如果檔案不存在,則會建立該檔案。

然後,我們使用 << 運算子將指定的文字追加到檔案中,最後關閉了檔案。

請務必如示例所示,在開啟檔案時檢查錯誤,以處理檔案無法開啟的情況。

使用 fstream 和 std::ios::app 旗標將文字追加到檔案中

與 ofstream 方法類似,您可以使用帶 std::ios::app 旗標的 std::fstream 開啟檔案,以便同時進行讀取和追加。

在 C++ 中,std::fstream 類別是標準樣板函式庫 (STL) 的一部分,用於檔案輸入和輸出。當您需要建立、開啟、寫入文字檔案或向其追加資料時,它也是一個極好的選擇。

std::ios::app 旗標是 std::fstream 的一個重要組成部分。套用它時,它會指示資料流以追加模式開啟檔案。

在此模式下,寫入資料流的任何資料都將被新增到現有檔案內容的末尾。如果檔案不存在,則會建立該檔案。

要使用帶 std::ios::app 旗標的 std::fstream 在 C++ 中將文字追加到檔案,可以按照以下步驟操作:

  • 包含必要的標頭檔:
    #include <fstream>
    #include <iostream>
    #include <string>
    
  • 建立一個 std::fstream 物件並以追加模式開啟檔案:
    std::fstream file("example.txt", std::ios::app);
    
  • 使用 if (!file.is_open()) 檢查檔案是否成功開啟。
  • 使用 file << textToAppend << std::endl; 將文字追加到檔案中,將 textToAppend 替換為您想要的文字。
  • 完成後使用 file.close(); 關閉檔案。

下面是完整的示例:

#include <fstream>
#include <iostream>
#include <string>

int main() {
  // Open the file in append mode
  std::fstream file("example.txt", std::ios::app);

  // Check if the file is opened successfully
  if (!file.is_open()) {
    std::cerr << "Error opening the file!" << std::endl;
    return 1;  // Exit with an error code
  }

  // Text to append
  std::string textToAppend = "This is the text to append.";

  // Append text to the file
  file << textToAppend << std::endl;

  // Close the file
  file.close();

  return 0;
}

這段程式碼將以追加模式開啟檔案,追加指定的文字,然後關閉檔案。

如果檔案不存在,則會建立該檔案。如果檔案存在,新內容將被新增到檔案末尾,而不會覆寫現有內容。

使用不帶旗標的 std::ofstream 將文字追加到檔案中

現在,如果您想建立一個新檔案或覆寫現有內容,可以使用不帶任何旗標的 std::ofstream。如果檔案已經存在,這將有效地清除其內容,從一張白紙開始。

下面是一個基本示例:

#include <fstream>
#include <iostream>

int main() {
  // Creating a new file or overwriting existing content
  std::ofstream outputFile("example.txt");

  // Checking if the file is successfully opened
  if (outputFile.is_open()) {
    outputFile << "This will overwrite existing content.\n";
    outputFile.close();  // Always close the file when done
  } else {
    std::cerr << "Unable to open the file.\n";
  }

  return 0;
}

在這段程式碼片段中,我們首先建立了一個名為 outputFile 的 std::ofstream 物件,並指定了要處理的檔案,在本例中為 example.txt。

使用 std::fstream 和 write() 方法將文字追加到檔案中

解決這個問題的另一個方法是在 fstream 物件中顯式呼叫 write() 成員函式,而不是像我們在前面的例子中那樣使用 << 操作符。這種方法對於大多數情況下應該會更快,但如果你有嚴格的效能要求,一定要對你的程式碼進行剖析並比較時間。

#include <fstream>
#include <iostream>

using std::cout;
using std::endl;
using std::fstream;
using std::string;

int main() {
  string text("Some huge text to be appended");
  string filename("tmp.txt");
  fstream file;

  file.open(filename, std::ios_base::app);
  if (file.is_open()) file.write(text.data(), text.size());
  cout << "Done!" << endl;

  return EXIT_SUCCESS;
}

在上面的程式碼中,我們使用 fstream 物件的 open() 方法以追加模式 (std::ios_base::app) 開啟了檔案。我們還使用 file.is_open() 檢查了檔案是否成功開啟。

然後,我們使用 write() 方法將文字作為二進位資料寫入檔案。正如我們所看到的,該方法接受兩個引數:一個指向資料的指標和要寫入的位元組數。

最後,我們印出了 Done!,以表明操作已完成。

結論

本文介紹的每種方法都為向檔案追加文字提供了一種獨特的方法。選擇哪種方法取決於您的具體要求和編碼風格。