ifstream: check if opened successfully

后端 未结 4 2010
猫巷女王i
猫巷女王i 2020-12-14 14:11

A colleague just told me that this code:

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

wou

4条回答
  •  悲&欢浪女
    2020-12-14 15:07

    You can also use is_open() to check if it worked, but ! is allowed (it's not checking for zero, it's a special overload of ! )

    edit:
    Just out of interest - why doesn't this throw an exception?
    Is it just that streams were introduced before exceptions
    or are we into the old C++ thing of - it's only an error not exceptional enough to be an exception.

提交回复
热议问题