从文件中删除特定行

时间:2014-10-26 18:59:40

标签: c++

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

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;

}

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

3 个答案:

答案 0 :(得分:4)

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

#include <iostream>
#include <fstream>

void eraseFileLine(std::string path, std::string eraseLine) {
std::string line;
std::ifstream fin;

fin.open(path);
std::ofstream temp; // contents of path must be copied to a temp file then renamed back to the path file
temp.open("temp.txt");

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

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

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

答案 1 :(得分:3)

试试这个:

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

答案 2 :(得分:0)

我想澄清一些事情。虽然gmas80提供的答案可能有用,但对我来说,它并没有。我不得不稍微修改它,这就是我最终的结果:

.panTo()

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

position = line.find(deleteLine);

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