从文本文件中删除最近添加的行

Delete recently added lines from a text file

本文关键字:添加 最近 删除 文本 文件      更新时间:2023-10-16

我正在用C++编写一个程序,它将行写入文本文件。在某些情况下,我希望它删除一堆最近添加的行。代码如下所示:

file << "Some line." << endl; // *
// lots of lines might be written to file here
if (condition2)
  // delete all the lines written to file since * including line "Some line."

我该怎么做?

看看 ostream 的seekptellp方法。

我假设你的file是某种流。

这只是一个伪代码,因为你也没有提供足够的信息

if (condition2)
{
   /*
    1. Read back the file lines till "Some line" marker
       in say, std::vector<std::string> 
    2. Discard other lines after that.
    3. Write the contents of std::vector into the file
  */
}