一位同事告诉我这段代码:
std::ifstream stream(filename.c_str());
if (!stream)
{
throw std::runtime_error("..");
}
Run Code Online (Sandbox Code Playgroud)
会错的.ifstream如果开放成功,他说评估为0.我的代码有效,但我想查找文档,但没有看到它说如何检查开放是否成功.你能指点我吗?
Oli*_*rth 46
operator! 超载的std::ifstream,这样你就可以做到这一点.
但在我看来,这是对运营商超载的严重滥用(由标准委员会).如果你这样做,那么你要检查的更明确if (stream.fail()).
小智 11
您可以通过使用正确的位掩码调用其ios :: exceptions()函数,使特定流在任何eof/fail/bad上抛出异常.因此,您可以在上面的初始问题中重写示例:
std::ifstream stream;
stream.exceptions(std::ios::failbit | std::ios::badbit);
stream.open(filename.c_str());
Run Code Online (Sandbox Code Playgroud)
在设置failbit或badbit时,stream将抛出异常.例如,如果ifstream :: open()失败,它将设置failbit并抛出异常.当然,如果在流上设置了这些位中的任何一个,这将引发异常,因此这个重写与初始示例不完全相同.你可以打电话
stream.exceptions(std::ios::goodbit);
Run Code Online (Sandbox Code Playgroud)
取消流上的所有异常并返回检查错误.