正在删除文件中的特定行

Deleting specific line from file

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

以下是我的示例文件的内容:

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");

但它不起作用。附带说明一下:该文件没有换行符/换行符。所以文件内容都写在一行中。

编辑:

固定代码:

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

这给了我预期的结果。感谢大家的帮助!

如果有人想要,我已经将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);
}

试试这个:

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

我想澄清一下。虽然gmas80提供的答案是可行的,但对我来说,它没有。我不得不对它进行一些修改,结果是:

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

另一件让我不满意的事情是它在代码中留下了空行。所以我写了另一件事来删除空白行:

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