所以我试图创建一个循环,通过文件读取行并根据行执行操作,除了某些行可以是另一个文件名,我需要打开并从该文件开始读取,同时将原始文件保留在堆栈上,这可能会发生多次,当新文件是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并交换了当前的ifstream并尝试将旧的ifstream推入堆栈,我&#39 ;我不确定这是否正常工作。
在我的if语句中,我尝试了一些事情,但似乎没有任何工作,以至于我遇到了麻烦。基本上,当我测试我的代码时,打开一个新的流工作并开始读入新文件,但我不完全确定如何重新回到旧的ifstream。
答案 0 :(得分:0)
在你的评论中,我觉得你可能正在寻找一个类似这样的结构:
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
}
}