如何在C++中删除文本文件中的特定行
How to delete a specific line in a text file in C++?
我想在文本文件中搜索字符串,并在找到时删除整行。我想用C++写这个。
我尝试过 C# 中的解决方案,并尝试创建临时文件。什么都不适合我。
这是我到目前为止的代码:
void MainForm::WriteToTextFile(){
ifstream stream("text.txt");
string line;
bool found = false;
while (std::getline(stream, line) && !found)
{
if (line.find("Delete_This_Line") != string::npos){ // WILL SEARCH "Delete_This_Line" in file
found = true;
line.replace(line.begin(), line.end(), "n");
stream.close();
}
我预计文本文件会被修改,但没有任何变化。
您不会向文件写入任何内容。
对于文本文件,您不能简单地"替换"文本,除非替换的长度与要替换的旧文本完全相同。
解决问题的一种常见方法是从原始文件读取,写入临时文件。找到要替换的文本后,将新文本写入临时文件。完成后,关闭两个文件,并将临时文件重命名为原始文件,将其替换为新修改的内容。
您只修改内存中的一个字符串,您怎么能期望更改读取文件的内容?
另请注意,要在关闭文件时继续尝试读取文件,在 getline() 之后测试发现太晚了,并且更简单的只是添加一个中断
std::getline
将行复制到内存中的另一个字符串对象。修改该字符串不会更改文件的内容。
一种可能的解决方案是使用输入和输出文件流重新创建文件,并避免仅复制所需的行。下面是一个未经测试的示例:
#include <fstream>
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
bool replace_line(string filename, string key, string new_content)
{
{
ifstream stream(filename);
ofstream ofs(filename + ".out");
string line;
bool found = false;
while (std::getline(stream, line))
{
if (line.find(key) != string::npos){
found = true;
ofs << new_content;
} else {
ofs << line;
}
}
}
remove(file);
rename(file + ".out", filename);
return found;
}
相关文章:
- 如何在我从C++文件中读取后立即删除行
- 删除 XML 文件中的子节点C++
- 如何在输入新内容 c++ 之前删除文件中的所有内容
- 如何更新和删除文本文件中的特定逗号分隔值?C++
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- 将内容从第一个文件("constituencies")移动到第二个文件("temp")并在之后重命名时,我的文件被删除
- 文件模式标志"ios::app"是否用于删除文件(如果文件已存在)?
- 如何自动获取我的项目的路径并删除一些文件
- C++ VS 错误:<实验/文件系统>提供 std::experimental::文件系统的标头已被Microsoft弃用,将被删除
- 如果我删除指针,我的C++程序会意外删除系统文件吗?
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- 文件删除(使用取消链接)与释放所有磁盘空间之间的延迟
- 重命名批处理文件(删除名称中的一些符号)(python/matlab/shell)
- 如何找到字符串并使用C 文件中的文件删除它
- 使用 DEF 文件删除 dll 导出的名称
- 关闭后等待文件删除
- c++中的文件删除
- 如何共享文件删除权限时,我打开一个文件ifstream
- 典型的Win32文件删除(IDropTarget::drop)实现
- 生成文件模式规则:循环生成文件.o < - 删除生成文件依赖项