读取和维护一堆输入流

Reading and maintaining a stack of input streams

所以我正在尝试创建一个循环,通过文件读取行并根据行执行操作,除了某些行可以是我需要打开并开始从该文件读取的另一个文件名,同时将原始文件保存在堆栈中,这可能会发生多次,当新文件为 EOF 时,我需要从堆栈中弹出前一个文件。

    std::ifstream* currentStream = fileStream;
    // this is within a class where I pass through fileStream in its initialization
    stack<std::ifstream*> fileStack = stack<std::ifstream*>();

    while(!fileStack.empty() || !currentStream->eof()){
      while (!currentStream->eof()) {
        getline(*currentStream, lineBuf);
        string line = trim(lineBuf);  
        if (line = blahblah) {
          //do stuff
        }
        else if (words[0] == "file") {
          auto params = extractParameters(line);
          std::ifstream simpFileStream;
          simpFileStream.open(params[1][0].substr(1, params[1][0].length()-2) + ".simp");
          currentStream->swap(simpFileStream);
          fileStack.push(&simpFileStream);
        }
        if(!fileStack.empty() && currentStream->eof()){
          // what to do here?
          fileStack.pop();
        }
      }
    }

在我的代码中,我尝试了几种方法,但这是我最后保存的,我基本上创建了一个新的 ifstream 并交换当前的,并尝试将旧的推入堆栈,我是不确定这是否能正常工作。

在我的 if 语句中,我尝试了一些方法,但似乎没有任何效果,这就是我遇到问题的地方。基本上当我测试我的代码时,打开一个新的流工作并且它开始读入新文件,但我不完全确定如何弹出回旧的 ifstream。

根据您的评论,我觉得您可能正在寻找类似这样的结构:

void method(std::string const& filename)
{
    // use smart pointers to avoid memory leaks
    std::stack<std::unique_ptr<std::ifstream>> files;

    // open initial file and push it to the top of the stack
    // to use as the 'current' file
    files.push(std::make_unique<std::ifstream>(filename));

    // use the top() of the stack as your 'current' file stream

    // as long as we have open files, keep going
    while(!files.empty())
    {
        // read the line in the loop control block
        for(std::string line; std::getline(*files.top(), line);)
        {
            if(line == "some stuff")
            {
                // start a new file on the top of the stack
                files.push(std::make_unique<std::ifstream>("new file name"));
            }
            else if(line == "some other stuff")
            {
                // do other stuff
            }
            // yet more stuff
        }

        // end of file reached here - pop
        // delete the current file stream off the top
        // of the stack (automatically closing the file)
        files.pop();
        // Now the top of the stack contains the previous current file stream
    }
}