I found a c++ code which uses ifstream to decide whether a file exists. That section is,
if (!ifstream(trajectory_file_name_)) {
cerr << "ERROR: The trajectory file:";
cerr << "\033[1;34m";
cerr << trajectory_file_name_;
cerr << "\033[0m";
cerr << " does not exist.";
cerr << endl;
exit(1);
}
what I have learned from the textbook (like "c++ primer plus") is something like, when judging whether a file exist via ifstream,
ifstream inFile(filename-);
if(!inFile.is_open())
{
return;
}
I have searched many website but didn't find any information on the first one. So I wonder if anyone can give me some explanation on the usage of ifstream of the first one. Thanks!
This comes down to how streams convert to bool
(or in this case it's due to operator!
, but same principle).
It's designed so that, for short, you can check for openness (and error flags) like:
std::ifstream ifs("path");
if (!ifs)
{
// ...
}
(Failure to open sets the failbit).
Your version just skips the declaration and does the same thing with a temporary.
Note that there are other reasons a file may not be openable, e.g. permissions. This is not a reliable way to check whether it exists and, even if it does, you have no way of guaranteeing that it will still exist in a moment when you try to do something with it.