Home > Enterprise >  How to delete specific line from text file c
How to delete specific line from text file c

Time:08-24

This is my text file content.

1
2
3

I want to delete line of this 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 to delete that line of my text file
        }
    }
    return 0;
}

how to delete that line in if statement?

CodePudding user response:

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.
  • Related