-1

I'm reading a file as below:

#include <fstream>

std::ifstream infile("example.txt");
for (std::string line; std::getline(infile, line);)
{
  std::cout << line << std::endl;
}

Now, I want to read the line and delete the line once I have read it. In the end, the example.txt should be empty. I'm wondering if there is any way I can do that in C++.

Thanks!

xxks-kkk
  • 2,336
  • 3
  • 28
  • 48
  • 4
    You cannot delete lines from a file without completely re-writing it. If you want the file ti be empty, open it as an ostream. –  Oct 22 '18 at 21:51
  • you can replace the lines though – Yucel_K Oct 22 '18 at 21:53
  • 3
    @Yucel_K Not in a text file, unless the "lines" are of fixed length. –  Oct 22 '18 at 21:54
  • ah.. i thought we could https://stackoverflow.com/questions/26576714/deleting-specific-line-from-file – Yucel_K Oct 22 '18 at 21:56
  • @NeilButterworth The motivation behind my question is that there is a certain part of files I want to continue to read next time. I only want to ignore (erase) the lines I have read before. I know I can keep track of `tellg` and erase the file when I'm done. But, I just wonder if there is any other better way? – xxks-kkk Oct 22 '18 at 21:59
  • 1
    It would be very inefficient to remove lines as you read. Keeping track of `tellg` locations sounds like a good method. Or (perhaps better) write to another file the lines you want to keep, then swap the files after. Or read the whole file into memory and then dump it back out after editing. – Galik Oct 22 '18 at 22:02
  • If the files are relatively small (few hundred lines are so), just read the lines you want to keep into a vector of strings and then truncate and re-write the lines to the file at the end. – David C. Rankin Oct 23 '18 at 00:07

1 Answers1

0

You can't just delete a line from the file. Think of a file like a fixed sized array, you can't erase the first element of an array because the memory for it is still there. All you can do is change what data it contains. That said what you can do is after you read the file you can erase the whole thing by opening it up with a std::ofstream. By default a std::ofstream will create a file if it doesn't exist and if it does then it will erase it and give you a blank file. That would look like

int main()
{
    std::ifstream infile("example.txt");
    for (std::string line; std::getline(infile, line);)
    {
      std::cout << line << std::endl;
    }
            Infile.close()
    std::ofstream{"example.txt"}; // erase the contents
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402