ifstream打开失败时如何获取错误消息 [英] How to get error message when ifstream open fails

查看:138
本文介绍了ifstream打开失败时如何获取错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 值时,如果另一个系统调用触发执行<$ c $之间的错误,则可能在多线程应用程序中有问题c> 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...

这篇关于ifstream打开失败时如何获取错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆