[英]How to write on a specific line of a file using c++
我正在嘗試編寫一個生成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();
}
為了解決您的問題,我建議您在修改文本時將文本讀入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:我沒有測試過代碼,但它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.