No exception throw after opening a file stream with files that do not exist?

I'm trying to use

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

If it file_namedoes not exist, an exception is not thrown. How can I be sure of this? I am using C ++ 11

+4
source share
1 answer

You can do this by setting an 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 thread failure conditions throw exceptions.

+10
source

Source: https://habr.com/ru/post/1569679/


All Articles