正在删除文件中的特定行
Deleting specific line from file
以下是我的示例文件的内容:
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;
}
相关文章:
- 如何在输入新内容 c++ 之前删除文件中的所有内容
- 文件模式标志"ios::app"是否用于删除文件(如果文件已存在)?
- 查找并删除文件 C++ 中的整行
- 如何删除文件中的数字,通过 c++ fstream 的
- 以编程方式防止重命名或删除文件,但仍使其可写
- C++ 如何使用_rmdir删除文件?
- 关于从驱动器中删除文件的问题
- Linux 从永远在线的应用程序中创建和删除文件
- 用户使用C++中的删除功能删除文件
- 如何在C++中删除文件中的一部分文本
- 我可以删除 *.o文件(代码:: blocks)
- 为什么std ::删除文件始终返回-1
- C++ 使用数字删除文件 io 行
- 如何使用 c++ 删除文件夹及其内容
- 如何在 C++ 中的文件处理中删除文件
- 用数字删除文件
- Cygwin:打开句柄时删除文件
- 接收文件并删除文件中的重复项
- 删除文件 C++ 中字符串中最后一个出现的字符
- 在循环内删除文件时使提升recursive_directory_iterator无效