读取文件时避免错误标志

Avoiding Error Flags when Reading Files

本文关键字:错误 标志 文件 读取      更新时间:2023-10-16

我通常是这样读取std::ifstream:

文件的
while (InFile.peek() != EOF)
{
    char Character = InFile.get();
    // Do stuff with Character...
}

这避免了在循环内使用if语句的需要。然而,似乎甚至peek()导致eofbit被设置,这使得调用clear()是必要的,如果我计划以后使用相同的流。

有更干净的方法吗?

通常,您只需使用

char x;
while(file >> x) {
    // do something with x
}
// now clear file if you want

如果您忘记清除(),那么使用基于RAII作用域的类。

编辑:如果有更多的信息,我就直接说
class FileReader {
    std::stringstream str;
public:
    FileReader(std::string filename) {
        std::ifstream file(filename);
        file >> str.rdbuf();
    }
    std::stringstream Contents() {
        return str;
    }
};

现在您可以只获得一个副本,而不必每次都清除()流。或者你可以有一个自清除引用。

template<typename T> class SelfClearingReference {
    T* t;
public:
    SelfClearingReference(T& tref)
        : t(&tref) {}
    ~SelfClearingReference() {
        tref->clear();
    }
    template<typename Operand> T& operator>>(Operand& op) {
        return *t >> op;
    }
};

我不太明白。Infile.peek()只设置eofbit当它返回EOF。如果它返回EOF,然后读取注定要失败;它设置eofbit的事实是一个优化,比什么都重要