ifstream 打开失败时如何获取错误消息

2021-12-26 00:00:00 error-handling stream c++ std
ifstream f;
f.open(fileName);

if ( f.fail() )
{
    // I need error message here, like "File not found" etc. -
    // the reason of the failure
}

如何以字符串形式获取错误信息?

How to get error message as string?

推荐答案

每个失败的系统调用都会更新 errno 值.

Every system call that fails update the errno value.

因此,您可以通过使用以下内容获得有关 ifstream 打开失败时会发生什么的更多信息:

Thus, you can have more information about what happens when a ifstream open fails by using something like :

cerr << "Error: " << strerror(errno);

<小时>

但是,由于每个系统调用都会更新全局errno值,如果另一个系统调用在两个系统调用之间触发错误,您可能会在多线程应用程序中遇到问题.f.open 的执行和 errno 的使用.


However, since every system call updates the global errno value, you may have issues in a multithreaded application, if another system call triggers an error between the execution of the f.open and use of errno.

在具有 POSIX 标准的系统上:

errno 是线程本地的;将其设置在一个线程中不会影响其任何其他线程中的值.

errno is thread-local; setting it in one thread does not affect its value in any other thread.

<小时>

编辑(感谢 Arne Mertz 和评论中的其他人):


Edit (thanks to Arne Mertz and other people in the comments):

e.what() 起初似乎是一种更符合 C++ 习惯的正确实现方式,但是此函数返回的字符串与实现相关且(至少在 G++ 的 libstdc++ 中)这个字符串没有关于错误背后原因的有用信息......

e.what() seemed at first to be a more C++-idiomatically correct way of implementing this, however the string returned by this function is implementation-dependant and (at least in G++'s libstdc++) this string has no useful information about the reason behind the error...

相关文章