ifstream f;
f.open(fileName);
if ( f.fail() )
{
// I need error message here, like "File not found" etc. -
// the reason of the failure
}
如何以字符串的形式获取错误信息?
发布于 2021-02-17 01:54:52
上面的std::system_error
示例稍有不正确。std::system_category()
将从系统的本地错误代码工具映射错误代码。对于*nix,这是errno
。对于Win32,它是GetLastError()
。即,在Windows上,上面的示例将打印出来
failed to open C:\path\to\forbidden: The data is invalid
因为EACCES是13,这是Win32错误代码ERROR_INVALID_DATA
要修复它,可以使用系统的本地错误代码工具,例如在Win32上
throw new std::system_error(GetLastError(), std::system_category(), "failed to open"+ filename);
或者使用errno和std::generic_category()
,例如
throw new std::system_error(errno, std::generic_category(), "failed to open"+ filename);
https://stackoverflow.com/questions/17337602
复制相似问题