删除.txt文件中的所有行,直到到达某个关键字
C++ Delete all lines in a .txt file up until a certain keyword is reached
我对c++相当陌生,我正在尝试编写一个代码来对大数据文件进行一些分析。我已经设法编写代码,生成一个文本文件,其中每行只显示一个单词/数字(有数百万行)。然而,前3000行左右包含了我的分析不需要的无用内容。
唯一的问题是,根据输入文件的不同,实际数据从不同的行号开始。
是否有办法编写一个快速代码,搜索文本文档并删除所有行,直到找到关键字"<event>"
?
更新:我成功了!可能比建议的要复杂一点,但它仍然有效。
谢谢你的帮助!
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
int counter = 0;
ifstream FileSearch("OutputVector.txt"); // search OutputVector input file.
while(!FileSearch.eof())
{
counter++;
string temp;
FileSearch >> temp;
if(temp == "<event>")
{
break; //While loop adding +1 to counter each time <event> is not found.
}
}
std::ofstream outFile("./final.txt"); //Create output file "final.txt."
std::string line;
std::ifstream inFile("OutputVector.txt"); //open input file OutputVector again.
int count = 0;
while(getline(inFile, line)){
if(count > counter-2){
outFile << line << std::endl;
}
count++; //while loop counts from counter-2 until the end and writes them to the new file.
}
outFile.close();
inFile.close(); //close the files.
remove("OutputVector.txt"); //Delete uneeded OutputVector File.
}
基本骨架:
std::ifstream stream("file name goes here")
std::string line;
// optional: define line number here
while (std::getline (stream, line))
{
// optional: increment line number here
if (line.find("<event>") != line.npos)
{ // Deity of choice help you if <event> naturally occurs in junk lines.
// Extra smarts may be required here.
doStuffWithRestOfFile(stream);
break;
}
}
没有足够的信息说明您希望如何修改源文件以回答子问题。一旦你把读者引开,如果你还没弄明白,就问一个新的问题。
编辑:短版
std::ifstream stream("file name goes here")
std::string line;
// optional: define line number here
while (std::getline (stream, line) && (line.find("<event>") == line.npos))
{
// optional: increment line number here
}
doStuffWithRestOfFile(stream);
如果你想用新版本覆盖文件(没有开头),你可以将所有文件读取到内存并覆盖它,或者在读取第一个文件的同时写入第二个文件,并将其移动/重命名为
读取所有行,直到找到<event>
:
std::ifstream input_file( filePath );
std::string line;
int current_line = 0;
do
{
std::getline( input_file, line );
++current_line;
}
while( line.find("<event>") == line.npos );
// use input_line to process the rest of the file
请记住,如果"<event>"
是第一行,那么在do while
之后,current_line
将包含1,而不是0
相关文章:
- extern 关键字在包含文件头文件C++
- 读取文本文件,其中C++读取特定关键字后面的值
- 使用关键字从文本文件返回数字
- 在特定字段中关键字搜索后,从文本文件中提取多个记录
- 如果我在标题文件中使用关键字的声明,则应该在定义本身中包含相同的关键字
- 如何在.cpp文件中使用C++关键字
- C++:定义类函数的.cpp文件中实例本身的表示关键字
- 如何在文件中搜索关键字,然后打印其中包含的字符串
- 具有多个文件的extern关键字
- 在二进制格式的xml文件中查找关键字
- 何时在带有头文件和目标文件的类方法中使用“inline”关键字
- 在 VC++ 中访问一个文件中声明的变量.(外部关键字用法)
- 使用关键字解析 C++ 中的文件
- C++ 在关键字段上联接两个管道分隔文件
- C++,逐行读取并搜索链接到文件中某行的关键字
- 不能对 c++ 类实现文件中的静态方法使用 "static" 关键字 (.cpp)
- 如果在头文件中定义方法,内联关键字有什么用?
- 这里需要extern关键字,cpp文件中的const
- 头文件与源/实现文件中关键字包含C++ "Rules"
- 当我们在该类的头文件中定义一个类成员函数时,必须使用内联关键字.为什么