c++ - 如何使用 fstream 删除文本文件中的特定行

标签 c++ fstream

美好的一天!我的问题是我应该删除我的文本文件中的整个特定行。但是相反,我只是用空白替换它。实际上,我不知道如何删除该行。这是我的代码:

fstream fs("FoodList.txt");
//charPos here is the position in file where I should begin deleting.
fs.seekp(charPos);
//I loop 100 times because I am sure that each row is 100 characters.
for (int i = 0; i < 100; i++)
{
    //What I really want to do is to delete the whole row
    fs << " ";
}

我的文本文件看起来像这样: 之前:

apple
banana
carrot
cherry

之后(如果我选择 charPos = 3):

apple
banana
cherry

顺便说一句,我已经制作了更新部分,我可以在其中编辑特定行。任何帮助将不胜感激! :)

最佳答案

最简单的方法是读入文件,写出到一个临时文件,排除所选行并将临时文件移动到原始文件。

关于c++ - 如何使用 fstream 删除文本文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25076739/

相关文章:

c++ - 使用仅安装了 Visual Studio 2017 的系统构建 Visual Studio 2010 C++ 项目

c++ - QT QImage - 将图像的子部分复制为多边形

c++ - 无法使用 Boost 正则表达式构建

c++ - "Incomplete type not allowed "创建 std::ofstream 对象时

c++ - fstream::open() Unicode 或非 Ascii 字符在 Windows 上不起作用(使用 std::ios::out)

c++ - 如何在文本文件中存储信息(字符串),然后甚至在C++中读取信息

c++ - CUDA 中的线程同步

c++ - 修改结构

c++ - 文件 I/O 错误复制构造函数 C++

c++ - 对齐 ofstream 的输出