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...
}
开发者_JAVA百科
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?
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;
}
};
I'm not sure I understand. Infile.peek()
only sets eofbit
when it returns EOF
. And if it returns EOF
, and later read
is bound to fail; the fact that it sets eofbit
is an
optimization, more than anything else.
精彩评论