Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifstream: check if opened successfully

Tags:

c++

iostream

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?

like image 243
Philipp Avatar asked Nov 17 '10 16:11

Philipp


People also ask

How do you check whether the file has opened successfully?

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.

How can I tell if a file failed to open?

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.

Is ifstream open?

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.

Does ifstream automatically close the file?

Note that any open file is automatically closed when the ifstream object is destroyed.


2 Answers

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()).

like image 148
Oliver Charlesworth Avatar answered Sep 22 '22 01:09

Oliver Charlesworth


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.

like image 45
Greg Satir Avatar answered Sep 19 '22 01:09

Greg Satir