删除特定行从文件

问题描述:

这是我的示例文件的内容:删除特定行从文件

abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA FIND ME akjsdkjhwjkjhasfkajbsdh ADHKJAHSKDJH

我需要找到并删除“FIND ME”文件的内部,从而输出是这样的:

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; 

} 

这让我我希望的结果。谢谢大家的帮助!

+0

你可以使用'sed'而不是C++吗?或者这是hw? – sbooth 2014-10-26 19:01:52

+0

文件中的所有内容都在一行中?你如何比较完整的句子和部分句子? – vinayawsm 2014-10-26 19:06:36

+0

如果可能,我宁愿不使用unix命令。这不是作业。我只是想为我自己的教育做点事情 – Venraey 2014-10-26 19:06:46

试试这个:

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

它工作!非常感谢! – Venraey 2014-10-26 19:11:17

+0

@Venraey:很高兴它的工作!你为什么不在你的问题中添加一个注释和一个固定版本的代码? ;) – gmas80 2014-10-26 19:15:34

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

我想澄清一些东西。尽管gmas80提供的答案可能有效,但对我而言,答案并非如此。我不得不稍微修改它,这是我结束了:

position = line.find(deleteLine); 

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

这并不能满足我的是它留在代码空行的另一件事。所以我写了另一件事删除空白行:

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