问题
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()?
回答1:
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()
.
来源:https://stackoverflow.com/questions/14920457/difference-between-casting-ifstream-to-bool-and-using-ifstreamis-open