Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

A colleague just told me that this code:

std::ifstream stream(filename.c_str());
if (!stream)
{
    throw std::runtime_error("..");
}

would be wrong. He said ifstream evaluates to 0 if opening is successful. My code works, but I wanted to find the documentation but didn't see where it says how to check if opening was successful. Can you point me to it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
528 views
Welcome To Ask or Share your Answers For Others

1 Answer

operator! is overloaded for std::ifstream, so you can do this.

In my opinion, though, this is a horrible abuse of operator overloading (by the standards committee). It's much more explicit what you're checking if you just do if (stream.fail()).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...