c++ - 为什么我可以将 ifstream 文件置于 if 条件中?

标签 c++ implicit-conversion

我正在尝试检查文件是否成功打开。我发现这种方法可以打开要读取的文件:

char path[]="data/configuration.txt";
std::ifstream configFile(path, std::ifstream::in);
if(configFile) {
  std::cout<<"Successfully opened file: "<<path<<std::endl;
} else {
  std::cout<<"Error, Could not open file: "<<path<<std::endl;
}

问题是 if 究竟检查了什么?

因为我还发现了以下检查文件是否打开的方法:

char path[]="data/configuration.txt";
std::ifstream configFile;
configFile.open(path, std::ifstream::in);
if(configFile.is_open()) {
  std::cout<<"Successfully opened file: "<<path<<std::endl;
} else {
  std::cout<<"Error, Could not open file: "<<path<<std::endl;
}

我还有其他问题。例如,这两种打开文件的方法有什么区别?另外,这两个 if 条件有什么区别?

我认为这些是最终得到相同结果的相似方法,因为我可以使用 std::ifstream 方法,如 is_open 两种打开方法:

std::ifstream configFile(path, std::ifstream::in);
configFile.open(path, std::ifstream::in);

最佳答案

std::ifstream可以 contextually convert to bool 通过 std::basic_ios<CharT,Traits>::operator bool ,它继承自 std::basic_ios .

Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().

请注意,它对 std::basic_ifstream<CharT,Traits>::is_open 执行不同的检查.

Checks if the file stream has an associated file. Effectively calls rdbuf()->is_open().

关于c++ - 为什么我可以将 ifstream 文件置于 if 条件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57818535/

相关文章:

c++ - 如何在数组中间构造开始和结束迭代器?

c++ - 检查成员是否存在并调用它或什么也不做

c# - 我可以/应该使用隐式运算符而不是覆盖 ToString 吗?

type-conversion - kotlin - 数字类型的自动转换

c++ - 为什么在初始化期间应用用户定义的转换?

C++ 嵌套类的新实例

c++ - 静态常量类成员的多重定义错误

c++函数参数char指针和字符串

Scala:为什么隐式找不到隐式 ExecutionContext?

Scala 原语到 AnyRef 的隐式转换