如何在C++中删除文本文件中的特定行

How to delete a specific line in a text file in C++?

本文关键字:文件 删除 C++ 文本      更新时间:2023-10-16

我想在文本文件中搜索字符串,并在找到时删除整行。我想用C++写这个。

我尝试过 C# 中的解决方案,并尝试创建临时文件。什么都不适合我。

这是我到目前为止的代码:

 void MainForm::WriteToTextFile(){
   ifstream  stream("text.txt");
   string line;
   bool found = false;
   while (std::getline(stream, line) && !found)
   {
    if (line.find("Delete_This_Line") != string::npos){ // WILL    SEARCH "Delete_This_Line" in file
        found = true;
        line.replace(line.begin(), line.end(), "n");
       stream.close();
      }

我预计文本文件会被修改,但没有任何变化。

您不会向文件写入任何内容。

对于文本文件,您不能简单地"替换"文本,除非替换的长度与要替换的旧文本完全相同。

解决问题的一种常见方法是从原始文件读取,写入临时文件。找到要替换的文本后,将新文本写入临时文件。完成后,关闭两个文件,并将临时文件重命名为原始文件,将其替换为新修改的内容。

您只修改内存中的一个字符串,您怎么能期望更改读取文件的内容?

另请注意,要在关闭文件时继续尝试读取文件,在 getline() 之后测试发现太晚了,并且更简单的只是添加一个中断

std::getline

行复制到内存中的另一个字符串对象。修改该字符串不会更改文件的内容。

一种可能的解决方案是使用输入和输出文件流重新创建文件,并避免仅复制所需的行。下面是一个未经测试的示例:

#include <fstream>
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
bool replace_line(string filename, string key, string new_content) 
{
    {
        ifstream stream(filename);
        ofstream ofs(filename + ".out");
        string line;
        bool found = false;
        while (std::getline(stream, line))
        {
            if (line.find(key) != string::npos){ 
                found = true;
                ofs << new_content;
            } else {
                ofs << line;
            }
        }
    }
    remove(file);
    rename(file + ".out", filename);
    return found;
}