C++读取然后编辑文本文件
C++ reading and then editing a text file
我想知道如何通过搜索包含foobar的行然后仅擦除这些行来读取和编辑文本文件。 不需要完整的程序,如果有人可以指出我正确的 fstream 函数。
#include <iostream>
#include <algorithm>
#include <string>
class line {
std::string data;
public:
friend std::istream &operator>>(std::istream &is, line &l) {
std::getline(is, l.data);
return is;
}
operator std::string() const { return data; }
};
int main() {
std::remove_copy_if(std::istream_iterator<line>(std::cin),
std::istream_iterator<line>(),
std::ostream_iterator<std::string>(std::cout, "n"),
[](std::string const &s) {
return s.find("foobar") != std::string::npos;
});
return 0;
}
执行以下操作:
string sLine = "";
infile.open("temp.txt");
while (getline(infile, sLine))
{
if (strstr(sLine, "foobar") != NULL)
cout<<sLine;
else
//you don't want this line... it contains foobar
}
infile.close();
cout << "Read file completed!!" << endl;
在这里,我将输出打印到控制台,而不是返回到文件,因为这应该为您指明正确的方向。
如果您需要有关如何将行打印到文件的提示,请阅读以下内容:
将所有不包含 foobar 的行保存到字符串中。读取整个文件后,将其关闭,然后使用写入权限打开它并将字符串写入其中。这也将覆盖旧内容。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入