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 打开失败时如何获取错误消息
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
