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()
?
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.
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.
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 .
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.
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()
.
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