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!,以表明操作已完成。

结论

本文介绍的每种方法都为向文件追加文本提供了一种独特的方法。选择哪种方法取决于您的具体要求和编码风格。