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

查看:4549
本文介绍了当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 value,在多线程应用程序中可能有问题,如果另一个系统调用触发执行 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.

编辑(感谢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 function useful information about the reason behind the error...

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

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