首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++删除.txt文件中的所有行,直到达到某个关键字为止

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

Stack Overflow用户
提问于 2015-06-04 01:45:50
回答 2查看 1.5K关注 0票数 0

我是C++的新手,我正在尝试编写一段代码来对大型数据文件运行一些分析。我已经成功地编写了生成文本文件的代码,其中每行只显示一个单词/数字(有数百万行)。然而,前大约3000行包含了我的分析不需要的东西。

唯一的问题是,根据输入文件的不同,实际数据从不同的行号开始。

有没有办法写一个快速的代码来搜索文本文档并删除所有行,直到找到关键字"<event>"为止?

更新:我让它工作了!可能比建议的要复杂一点,但它仍然有效。

谢谢你的帮助!

代码语言:javascript
复制
    #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.
}
EN

回答 2

Stack Overflow用户

发布于 2015-06-04 02:24:59

基本骨架:

代码语言:javascript
复制
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;
    } 
}

没有足够的信息说明您希望如何修改源文件来回答该子问题。一旦你让读者开始阅读,如果你还没有弄明白,就问一个新的问题。

编辑:简短版本

代码语言:javascript
复制
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);
票数 2
EN

Stack Overflow用户

发布于 2015-06-04 02:28:01

如果您想用新版本覆盖文件(没有开头),您可以将所有文件读取到内存并覆盖它,或者在读取第一个文件时写入第二个文件,然后移动/重命名它

要读取所有行,直到找到<event>

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30627168

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档