ifstream f;
f.open(fileName);
if ( f.fail() )
{
// I need error message here, like "File not found" etc. -
// the reason of the failure
}
如何以字符串的形式获取错误信息?
发布于 2016-04-14 12:35:51
根据@Arne Mertz的回答,从C++11开始,std::ios_base::failure
继承自system_error
(请参阅http://www.cplusplus.com/reference/ios/ios_base/failure/),其中包含strerror(errno)
将返回的错误代码和消息。
std::ifstream f;
// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
f.open(fileName);
} catch (std::system_error& e) {
std::cerr << e.code().message() << std::endl;
}
如果fileName
不存在,则输出No such file or directory.
。
发布于 2018-07-01 06:27:07
您还可以抛出一个std::system_error
,如下面的测试代码所示。这种方法产生的输出似乎比f.exception(...)
更具可读性。
#include <exception> // <-- requires this
#include <fstream>
#include <iostream>
void process(const std::string& fileName) {
std::ifstream f;
f.open(fileName);
// after open, check f and throw std::system_error with the errno
if (!f)
throw std::system_error(errno, std::system_category(), "failed to open "+fileName);
std::clog << "opened " << fileName << std::endl;
}
int main(int argc, char* argv[]) {
try {
process(argv[1]);
} catch (const std::system_error& e) {
std::clog << e.what() << " (" << e.code() << ")" << std::endl;
}
return 0;
}
输出示例(Ubuntu w/clang):
$ ./test /root/.profile
failed to open /root/.profile: Permission denied (system:13)
$ ./test missing.txt
failed to open missing.txt: No such file or directory (system:2)
$ ./test ./test
opened ./test
$ ./test $(printf '%0999x')
failed to open 000...000: File name too long (system:36)
发布于 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
复制相似问题