我是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.
}发布于 2015-06-04 02:24:59
基本骨架:
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);发布于 2015-06-04 02:28:01
如果您想用新版本覆盖文件(没有开头),您可以将所有文件读取到内存并覆盖它,或者在读取第一个文件时写入第二个文件,然后移动/重命名它
要读取所有行,直到找到<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
https://stackoverflow.com/questions/30627168
复制相似问题