如何使用c ++在文件的特定行上写入

问题描述 投票:0回答:1

我正在尝试编写一个生成html文件的代码。问题是在我的文件的第3行写这样的:

<html>
  <head>
    //here i need to write <title>sth</title>
  </head>

这是我试过的功能,但不起作用:(

void create_title(string a) {
  file.open("CTML.txt", ios::app || ios::in);
  for (int i = 0; i < 2; i++) {
    file.ignore(numeric_limits<streamsize>::max(), '\n');
  }
  file.seekp(file.tellg());
  file << "<title>"<< a << "</title>" << endl;
  file.close();
}
c++
1个回答
0
投票

为了解决您的问题,我建议您在修改文本时将文本读入std :: string,然后将其放回文件中。要做到这一点,你需要逐行读取文件,忽略第3行并输入其他内容,然后将其全部写回文件中。 我会建议像这样的代码:

#include <fstream> // Header with file io functions

void create_title(std::string str) {
    std::ifstream file("CTML.txt"); // Open the file.
    std::string new_file_content = "";
    std::string line;
    for (int i = 0; i < 2; i++) { // Read the first two lines of the file into new_file_content.
        std::getline(file, line);
        new_file_content += line + '\n';
    }
    std::getline(file, line); // Skip 3rd line
    new_file_content += "<title>" + str + "</title>"; // Put modified 3rd line in new_file_content instead.
    while (std::getline(file, line)) // Read the rest of the file in new_file_content.
        new_file_content += line + '\n';
    file.close(); // Close the file.
    std::ofstream file_for_out("CTML.txt"); // Open the file for writing.
    file_for_out << new_file_content; // Write the new file content into the file.
}

祝美好的一天,阿米莉亚。 PS:我没有测试过代码,但它应该可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.