[英]Get std::fstream failure error messages and/or exceptions
我正在使用 fstream。 有没有办法获得失败消息/异常?
例如,如果我无法打开文件?
默认情况下,流不会在错误时引发异常,它们会设置标志。 您可以使用流的exception()成员函数使它们引发异常:
ifstream ifs;
ifs.exceptions( std::ios::failbit ); // throw if failbit get set
从理论上讲,您可以执行以下操作:
try {
int x;
ifs >> x;
}
catch( const std::exception & ex ) {
std::cerr << "Could not convert to int - reason is "
<< ex.what();
}
不幸的是,C ++ Standard没有指定抛出的异常包含任何错误消息,因此您在此处是实现特定的领域。
简短的回答:不。 即使在各种操作后检测到故障(使用bad()
, fail()
)之后检查errno
也无法可靠地工作。 创建ifstream
/ ofstream
包裹无法打开的文件并不一定会设置失败位,直到您尝试读取,写入或关闭它。
长答案:您可以调用ios::exceptions(ios_base::iostate)
来请求在设置了相应的位(badbit,failbit,eofbit)时引发ios_base::ios_failure
异常,但这(至少在GNU和Microsoft C ++上)库)不会比手动检查这些位给您更多的信息,并且最终导致毫无意义的恕我直言。
通过检查,我发现errno
和GetLastError()
都设置了最后一个错误,检查它们非常有帮助。 要获取字符串消息,请使用:
strerror(errno);
如果您正在寻找比std::ios_base::failure
提供的更详细的消息,那么这里是一个使用errno
重新引发std::system_error
的示例:
terminate called after throwing an instance of 'std::system_error'
what(): broken/path: No such file or directory
#include <fstream>
int main() {
const std::string filename{ "broken/path" };
try {
std::ifstream file{ filename };
file.exceptions(std::ios::failbit); // std::ios_base_failure is thrown here
} catch (std::ios_base::failure&) {
throw std::system_error{ errno, std::generic_category(), filename };
}
}
这适用于 UNIX 和 Windows,因为“所有errno
值都……与 UNIX 兼容”( source )。
如果您想要更具体的Windows 错误代码(即文件已经在另一个程序中打开),您应该查看特定于平台的GetLastError()
api 而不是errno
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.