我正在尝试编写一个生成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();
}
答案 0 :(得分:0)
为了解决您的问题,我建议您在修改文本的同时将其读取到std :: string中,然后再将其放回文件中。为此,您需要逐行读取文件,忽略第三行,而放其他东西,然后将其全部写回到文件中。
我建议这样的代码:
#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.
}
Amelia,祝您有美好的一天。
PS:我尚未测试过代码,但应该可以。