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

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

问题描述

当 C++ 流打开失败时,有没有办法获得特定的错误条件?也就是说,它是否因为文件不存在而失败,或者权限错误等等.基本上我正在寻找与普通 C 中 fopen() 的 errno 等效的功能.

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天全站免登陆