【问题标题】:Deleting specific line from file从文件中删除特定行
【发布时间】:2023-10-03 16:10:01
【问题描述】:

这些是我的示例文件的内容:

abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA FIND ME akjsdkjhwjkjhasfkajbsdh ADHKJAHSKDJH

我需要在文件中找到并删除“找到我”,这样输出就会如下所示:

abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA akjsdkjhwjkjhasfkajbsdh ADHKJAHSKDJH

我尝试了下面的getline方法,然后将除FIND ME之外的所有内容写入一个临时文件,然后将临时文件重命名回来。

string deleteline;
string line;

ifstream fin;
fin.open("example.txt");
ofstream temp;
temp.open("temp.txt");
cout << "Which line do you want to remove? ";
cin >> deleteline;



while (getline(fin,line))
{
    if (line != deleteline)
    {
    temp << line << endl;
    }
}

temp.close();
fin.close();
remove("example.txt");
rename("temp.txt","example.txt");

但它不起作用。 顺便说一句:该文件没有换行符/换行符。所以文件内容都写在1行。

编辑:

固定代码:

while (getline(fin,line))
{
    line.replace(line.find(deleteline),deleteline.length(),"");
    temp << line << endl;

}

这让我得到了我预期的结果。谢谢大家帮忙!

【问题讨论】:

  • 你能用sed代替C++吗?还是这是硬件?
  • 文件中的所有内容都在一行中?你如何比较完整的句子和部分句子?
  • 如果可能,我宁愿不使用 unix 命令。这不是家庭作业。我只是想为自己的教育做些事情
  • @VinayKumar 我实际上尝试用换行符分隔每一行,但由于某种原因它也不起作用。但是,是的,我需要在文件中找到一行并从那里删除它。
  • 我在visual studio中没有getline(fin, line)这个函数。

标签: c++


【解决方案1】:

如果有人愿意,我已将 Venraey 的有用代码转换为函数:

#include <iostream>
#include <fstream>
    
void eraseFileLine(std::string path, std::string eraseLine) {
    std::string line;
    std::ifstream fin;
    
    fin.open(path);
    // contents of path must be copied to a temp file then
    // renamed back to the path file
    std::ofstream temp;
    temp.open("temp.txt");

    while (getline(fin, line)) {
        // write all lines to temp other than the line marked for erasing
        if (line != eraseLine)
            temp << line << std::endl;
    }

    temp.close();
    fin.close();

    // required conversion for remove and rename functions
    const char * p = path.c_str();
    remove(p);
    rename("temp.txt", p);
}

【讨论】:

    【解决方案2】:

    试试这个:

    line.replace(line.find(deleteline),deleteline.length(),"");
    

    【讨论】:

    • @Venraey:很高兴它成功了!为什么不在问题中添加注释和固定版本的代码? ;)
    【解决方案3】:

    我想澄清一些事情。尽管 gmas80 提供的答案可以工作,但对我来说,它没有。我不得不对其进行一些修改,这就是我最终得到的结果:

    position = line.find(deleteLine);
    
    if (position != string::npos) {
        line.replace(line.find(deleteLine), deleteLine.length(), "");
    }
    

    另一件让我不满意的事情是它在代码中留下了空白行。于是我又写了一个删除空行的东西:

    if (!line.empty()) {
        temp << line << endl;
    }
    

    【讨论】: