当C ++流打开失败时,你能得到一个特定的错误条件吗? [英] Can you get a specific error condition when a C++ stream open fails?

查看:75
本文介绍了当C ++流打开失败时,你能得到一个特定的错误条件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当C ++流打开失败时,有没有办法得到特定的错误条件?也就是说,它是否失败,因为文件不存在或权限错误等。基本上我正在寻找功能等同于errno for fopen()在纯C。

Is there any way to get a specific error condition when a C++ stream open fails? That is, whether it failed because the file didn't exist, or permissions were wrong, or etc. Basically I'm looking for functionality equivalent to errno for fopen() in plain C.

GCC似乎正确地设置了errno,但这似乎并不是C ++标准所要求的,我不能确定这是否只是一个实现流的工具,或一个故意的功能(和因此我不知道它是否会跨版本持久化。)

GCC seems to set errno properly, but that doesn't seem to be required by the C++ standard and I can't determine whether this is just an artifact of the way they implemented streams, or a deliberate feature (and thus I don't know whether it will persist across versions).

有一种方法可靠地获得这个信息,无论是标准C ++还是非意外地在一个更多主要编译器?

Is there a way to get this info reliably, either in standard C++ or non-accidentally in one or more major compilers?

推荐答案

您可以查看ios标志(badbit,eofbit,failbit,goodbit)
使用ios :: bad(),ios :: fail(),ios :: eof()或ios :: good()更容易测试。
也可以使用ios :: exceptions()将流设置为在错误时生成异常。

You can look at the ios flags (badbit, eofbit, failbit, goodbit) for general reasons. Testing will is easier using ios::bad(), ios::fail(), ios::eof(), or ios::good(). The stream can also be set to generate exceptions on error, using ios::exceptions().

详细的I / O错误报告可能在某些实现,正如你指出GCC。对于不同的编译器,您可能需要依赖此行为。如果有多个编译器的机会,请确保测试,并可能包括预处理器语句来检查当前的编译器等。

据我所知,唯一的其他地方,它讨论的是建议的TR2添加

Detailed I/O Error Reporting may be available in some implementations, as you point out for GCC. You may have to rely on this behavior for the different compilers. If there is a chance for multiple compilers, make sure to test and probably include preprocessor statements to check the current compiler, etc.
As far as I know, the only other place it's discussed is in proposed TR2 additions.

这篇关于当C ++流打开失败时,你能得到一个特定的错误条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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