Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between casting ifstream to bool and using ifstream::is_open()

Maybe a dummy question, but I need a clear answer to it. Is there any difference at all in the return of any of those functions

int FileExists(const std::string& filename)
{
  ifstream file(filename.c_str());
  return !!file;
}

int FileExists(const std::string& filename)
{
  ifstream file(filename.c_str());
  return file.is_open();
}

So in other words, my question is: does casting the fstream to bool give exactly the same result as fstream::is_open()?

like image 298
The Quantum Physicist Avatar asked Feb 17 '13 11:02

The Quantum Physicist


People also ask

What is the difference between ifstream and istream?

ifstream is input file stream which allows you to read the contents of a file. ofstream is output file stream which allows you to write contents to a file. fstream allows both reading from and writing to files by default.

What is the purpose of ifstream class?

These include ifstream, ofstream and fstream classes. These classes area derived from fstream and from the corresponding iostream class. These classes, designed to manage the disk files, are declared in fstream and therefore we must include this file in any program that uses files. ios stands for input output stream.

What does ifstream Infile do in C++?

ifstream infile ("file-name"); The argument for this constructor is a string that contains the name of the file you want to open. The result is an object named infile that supports all the same operations as cin , including >> and getline .

Is ifstream a variable?

An ifstream variable has an open function which can be used to open a file. The name of the file is a parameter to the open function. Once this is done, you can read from the ifstream object in exactly the same way you would read from cin.


1 Answers

No. is_open checks only whether there is an associated file, while a cast to bool also checks whether the file is ready for I/O operations (e.g. the stream is in a good state) (since C++11).

is_open

Checks if the file stream has an associated file.

std::basic_ios::operator bool

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

like image 125
Zeta Avatar answered Sep 23 '22 21:09

Zeta