How to get error message when ifstream open fails(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
值,如果另一个系统调用在两个系统调用之间触发错误,您可能会在多线程应用程序中遇到问题.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 打开失败时如何获取错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ifstream 打开失败时如何获取错误消息


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01