Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between (!file) and (!file.is_open())?

Tags:

c++

fstream

What is the difference between if(!file) and if(!file.is_open())? I use them for checking if a file has successfully been opened/read or not.

#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 
   . . .
}
like image 507
abunehneh Avatar asked Sep 01 '25 10:09

abunehneh


2 Answers

The c++ documentation explains that operator!

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

On the other hand, is_open()

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

If you want to know if the file successfully opened, use is_open(). It is more expressive of your intentions as well.

like image 163
Philip Nelson Avatar answered Sep 03 '25 02:09

Philip Nelson


If you read the documentation, you'll see that operator! returns whether an error has occurred. While is_open returns whether the stream has an associated file. Two very different things.

like image 34
Jesper Juhl Avatar answered Sep 03 '25 03:09

Jesper Juhl