Search code examples
c++filec++11fstream

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


This is my text file content.

1
2
3

I want to delete a line in that file.

#include <iostream>
#include <fstream>
#include <string>
std::fstream file("havai.txt", ios::app | ios::in | ios::out);

int main()
{
    std::string line;
    int number;
    std::cout << "Enter the number: ";
    std::cin >> number;
    while (file.good())
    {
        getline(file, line);
        if (std::to_string(number) == line)
        {
            // How can I delete that line of my text file?
        }
    }
    return 0;
}

How can I delete that line in the if statement?


Solution

  • Removing data from a file is far more complicated than it appears. It is almost always orders of magnitude easier to create a new file and write the information to be kept into it.

    1. Open File A for reading.
    2. Open File B for writing.
    3. For each line in File A: If it's not a line to be discarded, write it to File B.
    4. Close File A
    5. Close File B
    6. Replace File A with File B.