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?
You can check if a file has been correctly opened by calling the member function is_open(): bool is_open(); that returns a bool type value indicating true in case that indeed the object has been correctly associated with an open file or false otherwise.
You can use is_open() to check if the file was successfully opened. If file is ! open then cout the Error and force rentry via a loop.
std::ifstream::is_openReturns whether the stream is currently associated to a file. Streams can be associated to files by a successful call to member open or directly on construction, and disassociated by calling close or on destruction.
Note that any open file is automatically closed when the ifstream object is destroyed.
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())
.
You can make a particular stream throw an exception on any of eof/fail/bad by calling its ios::exceptions() function with the proper bitmask. So, you could rewrite the example in the initial question above as:
std::ifstream stream; stream.exceptions(std::ios::failbit | std::ios::badbit); stream.open(filename.c_str());
Here stream will throw an exception when the failbit or badbit gets set. For example if ifstream::open() fails it will set the failbit and throw an exception. Of course, this will throw an exception later if either of these bits gets set on the stream, so this rewrite is not exactly the same as the initial example. You can call
stream.exceptions(std::ios::goodbit);
to cancel all exceptions on the stream and go back to checking for errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With