将ifstream转换为bool与使用ifstream :: is_open()之间的区别 [英] Difference between casting ifstream to bool and using ifstream::is_open()

查看:391
本文介绍了将ifstream转换为bool与使用ifstream :: is_open()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许是一个虚拟的问题,但我需要一个明确的答案.这些函数的返回是否有任何区别

Maybe a dummy question, but I need a clear answer to it. Is there any difference at all in the return of any of those functions

int FileExists(const std::string& filename)
{
  ifstream file(filename.c_str());
  return !!file;
}

int FileExists(const std::string& filename)
{
  ifstream file(filename.c_str());
  return file.is_open();
}

换句话说,我的问题是:将fstream强制转换为bool会得到与fstream :: is_open()完全相同的结果吗?

So in other words, my question is: does casting the fstream to bool give exactly the same result as fstream::is_open()?

推荐答案

否. is_open仅检查是否存在关联的文件,而强制转换为bool的对象还检查文件是否已准备好进行I/O操作(例如,流处于良好状态)(自C ++ 11起). /p>

is_open

No. is_open checks only whether there is an associated file, while a cast to bool also checks whether the file is ready for I/O operations (e.g. the stream is in a good state) (since C++11).

检查文件流中是否有关联的文件.

Checks if the file stream has an associated file.

std::basic_ios::operator bool

如果流没有发生错误并且可以进行I/O操作,则返回true.具体来说,返回!fail().

这篇关于将ifstream转换为bool与使用ifstream :: is_open()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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