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
true
if an error has occurred on the associated stream. Specifically, returnstrue
ifbadbit
orfailbit
is set inrdstate()
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.
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