Search code examples
c++filestream

How can I delete a line from a text file in C++?


I want to delete a line of my text file without replacing it with " ". Just as a side note: my file has newlines. So I have more than one line (like a table)

void Data::delete_line(const string& idNr) {
    ifstream list;
    string readFile, id;
    list.open("list.txt", ios::app);

    if (list.is_open()) {
        while (getline(list, readFile)) {
            int pos = readFile.find(';');
            id = readFile.substr(0, pos);
            if (idNr == id) {
                //deleting the line here
            }
        }
    }

}

I found this question but it does not solve my problem:


Solution

  • Maybe you can just create a new file and put your data into the new file. Like this:

    void Data::delete_line(const string& idNr) {
    ifstream list;
    ofstream outFile("newList.txt");
    string readFile, id;
    
    list.open("list.txt", ios::app);
    
    if (list.is_open()) {
        while (getline(list, readFile)) {
            int pos = readFile.find(';');
            id = readFile.substr(0, pos);
            if (idNr != id) {
                outFile << readFile;
            }
        }
    }
    list.close();
    outFile.close();
    
    remove("list.txt");
    rename("newList.txt", "list.txt");
    }
    

    At the end you just remove your old file and rename the new file with the name of the old file. I hope this will solve your problem.