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
. . .
}
The c++ documentation explains that operator!
Returns
trueif an error has occurred on the associated stream. Specifically, returnstrueifbadbitorfailbitis set inrdstate()
On the other hand, is_open()
Checks if the file stream has an associated file. Returns
trueif the file stream has an associated file,falseotherwise
If you want to know if the file successfully opened, use is_open(). It is more expressive of your intentions as well.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With