而(file_object)是一个导致无限循环

While(file_object) is an causing infinite loop

本文关键字:一个 无限循环 file object      更新时间:2023-10-16

这似乎很奇怪。我有一段代码,如下所示:

List(const char* fn) {
    std::ifstream file(fn);
    if (!file){
        throw std::string("*** Failed to open file ") + std::string(fn) + std::string(" ***");
    }
    while (file) {
        T e;
        if (e.load(file)){
            list.push_back(*new T(e));
        }
    }
}

对于其他人,它似乎可以很好地运行整个文件。但对我来说,我被困在我的机器上的无限循环中。

OS X - g++ 4.2

我不知道为什么这里有功能差异。

这是无限循环:

while (file) {
    T e;
    if (e.load(file)){
        list.push_back(*new T(e));
    }
}
只要

文件保持有效状态,while(file)就会返回 true。

您还没有告诉我们什么是T或其load方法的作用,因此我们无法为您提供比这更多的信息。您需要确保 load 方法要么关闭文件描述符,要么将其保留eof状态或其他类似状态。