【发布时间】:2023-03-05 05:56:01
【问题描述】:
如何在 C++ 中删除/替换文件的最后一行?我看了这些问题: Deleting specific line from file,Read and remove first (or last) line from txt file without copying 。我想过迭代到文件的末尾,然后替换最后一行,但我不知道该怎么做。
【问题讨论】:
如何在 C++ 中删除/替换文件的最后一行?我看了这些问题: Deleting specific line from file,Read and remove first (or last) line from txt file without copying 。我想过迭代到文件的末尾,然后替换最后一行,但我不知道该怎么做。
【问题讨论】:
查找文件内容中最后一次出现“\n”的位置。如果文件以'\n'结尾,即在最后一个'\n'之后没有更多数据,则查找上一个'\n'出现的位置。使用resize_file在找到的位置截断文件或只替换找到位置之后的内容。
【讨论】:
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("input.txt");
ofstream fout("output.txt");
while (!fin.eof()) {
string buffer;
getline(fin, buffer);
if (fin.eof()) {
fout << "text to replace last line";
} else {
fout << buffer << '\n';
}
}
fin.close();
fout.close();
}
您还可以读取和存储所有输入文件,修改然后写入:
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
// read
ifstream fin("input.txt");
vector<string> lines;
while (!fin.eof()) {
string buffer;
getline(fin, buffer);
lines.push_back(buffer + '\n');
}
fin.close();
// modify
lines[lines.size() - 1] = "text to replace last line";
// write
ofstream fout("output.txt");
for (string line: lines) { // c++11 syntax
fout << line;
}
fout.close();
}
【讨论】:
fin.eof() 在循环体中始终为 false。
(getline(fin, buffer)) 为真,则fin.eof() 为假。