c++ - (!file) 和 (!file.is_open()) 有什么区别?

标签 c++ fstream

if(!file)if(!file.is_open()) 有什么区别? 我用它们来检查文件是否已成功打开/读取。

#include<iostream>
#include<fstream>
using namespace std;

int main(){
ifstream file;

// first one
if (!file) 
   cout<<"File is not opened"<<endl;
else 
   . . .

//second one
if (!file.is_open()) 
   cout<<"File is not opened"<<endl;
else 
   . . .
}

最佳答案

c++ 文档解释了 operator!

Returns true if an error has occurred on the associated stream. Specifically, returns true if badbit or failbit is set in rdstate()

另一方面,is_open()

Checks if the file stream has an associated file. Returns true if the file stream has an associated file, false otherwise

如果您想知道文件是否成功打开,请使用is_open()。它也更能表达您的意图。

关于c++ - (!file) 和 (!file.is_open()) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59919741/

相关文章:

c++ - glGenVertexArrays 上的 OpenGL C++ glfw 3 glew 错误 1282

c++ - 在 C++ 中使用模板函数确定常量

c++ - 如何使用行位置在 std::ifstream 中导航?

c++ - 读/写几个未知大小的结构到文件 C++

c++ - 无法覆盖文件的特定位置。覆盖特定位置会删除其之前的所有内容并将其后的值移动

c++ - 打开一个文件,修改每个字符然后做反向操作不输出原始文件

c++ - 从文本文件读取到数组

c++ - 如何在不使用中间变量的情况下初始化包含数组的 constexpr 结构?

c++ - 覆盖语法,返回指向固定大小数组的指针的专用模板方法

c++ - 为什么 auto_ptr<T> 没有定义 operator!() ?