0

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.

olimpiabaku
  • 151
  • 11

2 Answers2

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
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