How do I remove/replace the last line of a file in C++? I looked at these questions: Deleting specific line from file, Read and remove first (or last) line from txt file without copying . I thought about iterating to the end of the file and then replacing the last line but I'm not sure how to do that.
Asked
Active
Viewed 894 times
2 Answers
0
#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();
}
Also you can read and store all your input file, modify and then write it:
#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();
}

Meowster
- 447
- 3
- 14
-
`fin.eof()` is always false in the loop body. – 273K Jun 20 '21 at 15:47
-
@S.M. I just read the link you provided, how can I go to the end of file without using eof? – olimpiabaku Jun 20 '21 at 15:48
-
The link's answers contain the information to the error in your code, but the question title may confuse. I removed the link. – 273K Jun 20 '21 at 15:50
-
@Meowster Nope. If `(getline(fin, buffer))` is true, then `fin.eof()` is false. – 273K Jun 20 '21 at 15:54
-
https://wandbox.org/permlink/LEdegHHks7pefPoj true is never output. – 273K Jun 20 '21 at 16:37
-
this is because your last line is empty and getline just ignores it. yes I see problem here, but not with eof – Meowster Jun 20 '21 at 20:58
-
I changed the code, so now it covers cases when your last line is empty as in your example – Meowster Jun 20 '21 at 21:13
0
Find the position of the last occurrence of '\n' in the file content. If the file ends with '\n', i.e there is no more data after the last '\n', then find the position of the previous occurrence of '\n'. Use resize_file to truncate files at the found position or just replace the content after the found position.

273K
- 29,503
- 10
- 41
- 64