锐英源软件
第一信赖

精通

英语

开源

擅长

开发

培训

胸怀四海 

第一信赖

当前位置:锐英源 / 开源技术 / 语音识别开源 / ifstream的is_open和fail哪个好?

服务方向

人工智能数据处理
人工智能培训
kaldi数据准备
小语种语音识别
语音识别标注
语音识别系统
语音识别转文字
kaldi开发技术服务
软件开发
运动控制卡上位机
机械加工软件
软件开发培训
Java 安卓移动开发
VC++
C#软件
汇编和破解
驱动开发

联系方式

固话:0371-63888850
手机:138-0381-0136
Q Q:396806883
微信:ryysoft

ifstream的is_open和fail哪个好?

重点

流的使用对初学者非常难,但掌握了要点就容易,流被C++封装包装的很全面,判断对象好坏,直接用对象就行了,不用成员函数更好。


Reading Savitch's Problem Solving in C++, std::ifstream::fail is shown as an example to check if a file has been correctly opened (ifstream or ofstream). 读取Savitch的C ++问题解决方法,以std :: ifstream :: fail为例检查文件是否已正确打开(ifstream或stream)。

I've previously used, as it is what I was first shown, std::ifstream::is_open to perform the same check. 我以前曾经使用过std :: ifstream :: is_open来执行相同的检查,因为这是我第一次看到的内容。

Which is 'better' practice? 哪种“更好”的做法?

Or in the case that either one is called directly after attempting to open, does it make no practical difference? 或者,如果在尝试打开后直接调用其中任何一个,是否没有实际区别?

 

INTRODUCTION

std::ifstream::fail includes checking std::ifstream::is_open, but std::ifstream::is_open only checks if it was possible to create a handle to the file. std :: ifstream :: fail包括检查std :: ifstream :: is_open,但是std :: ifstream :: is_open仅检查是否可以创建文件的句柄。

EXPLANATION

std::ifstream::fail can return true, even if std::ifstream::is_open returns true; they are not the mutually exclusive. 即使std :: ifstream :: is_open返回true,std :: ifstream :: fail也可以返回true;它们不是互斥的。

.fail will check the overall "health" of the stream, which involves things such as checking the stream has currently entered a fail state from trying to read an invalid value, whereas .is_open will only check if the stream is currently attached to a file, .is_open doesn't care if the stream is in a fail state, or not. .fail将检查流的整体``运行状况'',其中包括检查流当前是否已尝试读取无效值而进入失败状态,而.is_open将仅检查流当前是否已附加到文件,.is_open无关流是否处于失败状态。

WHAT'S THE BETTER PRACTICE?

This certainly depends on what you are trying to accomplish. 这当然取决于您要完成的工作。

Normally it's recommended to rely on the explicit operator bool () to see if a stream is ready to be read/written to. This includes checking the overall health of the stream. 通常建议使用显式运算符bool()来查看是否已准备好读取/写入流。这包括检查流的总体运行状况。

Can we make another read/write operation on some_stream? 我们可以对some_stream进行另一次读/写操作吗?

if (some_stream) {
    // stream is alive and well
} else {
    // something is wrong
}  

If you explicitly would like to see if some fstream is actually attached to a file, use is_open, and if you want to check the overall health; use .fail or rely on the fact that a stream is convertiable to 如果您明确希望查看某个fstream是否确实附加到文件上,请使用is_open,以及是否要检查整体运行状况;使用.fail或依赖于流可转换为的事实

 

 

Use the bool conversion operator instead! 请改用布尔转换运算符!

ifstream i("test.txt");  if (i) {      //success  }  

Or better: 或更好:

ifstream i("test.txt");  if (!i) {      //failure, handle error  }
友情链接
版权所有 Copyright(c)2004-2021 锐英源软件
公司注册号:410105000449586 豫ICP备08007559号 最佳分辨率 1024*768
地址:郑州大学北校区院(文化路97号院)内