删除.txt文件中的所有行,直到到达某个关键字

C++ Delete all lines in a .txt file up until a certain keyword is reached

本文关键字:关键字 文件 txt 删除      更新时间:2023-10-16

我对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