c++while-loopfilestreams

Avoiding Error Flags when Reading Files


This is how I usually read files with std::ifstream:

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

This avoids the need of an if statement inside the loop. However, it seems that even peek() causes eofbit to be set, which makes calling clear() necessary if I plan on using that same stream later.

Is there a cleaner way to do this?


Solution

  • Typically, you would just use

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

    If you forget to clear(), then use an RAII scope-based class.

    Edit: Given a little more information, I'd just say

    class FileReader {
        std::stringstream str;
    public:
        FileReader(std::string filename) {
            std::ifstream file(filename);
            file >> str.rdbuf();
        }
        std::stringstream Contents() {
            return str;
        }
    };
    

    Now you can just get a copy and not have to clear() the stream every time. Or you could have a self-clearing reference.

    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;
        }
    };