Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No exception throw after open a file stream with non-exist files?

Tags:

c++

I am trying to use

std::ifstream inStream;
inStream.open(file_name);

If file_name does not exists, no exception is thrown. How can I make sure to throw in this case? I am using C++11

like image 853
Adam Lee Avatar asked Jan 02 '15 09:01

Adam Lee


1 Answers

You can do so by setting the streams exception mask, before calling open()

std::ifstream inStream;
inStream.exceptions(std::ifstream::failbit);
try {
    inStream.open(file_name);
}
catch (const std::exception& e) {
    std::ostringstream msg;
    msg << "Opening file '" << file_name 
        << "' failed, it either doesn't exist or is not accessible.";
    throw std::runtime_error(msg.str());
}

By default none of the streams failure conditions leads to exceptions.

like image 65
πάντα ῥεῖ Avatar answered Oct 20 '22 16:10

πάντα ῥεῖ