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.
- Open File A for reading.
- Open File B for writing.
- For each line in File A: If it's not a line to be discarded, write it to File B.
- Close File A
- Close File B
- Replace File A with File B.