I am using the following piece of code to check whether file is existing or not using
std::ifstream
#include <iostream>
#include <fstream>
int main()
{
if (std::ifstream("file.txt"))
{
std::cout << "File present\n";
}
return 0;
}
std::ifstream
Actually you are using unnamed temporary object of std::ifstream
. It is not required to call std::ifstream::close()
, as the object is being destroyed after usage, and it's destructor closes the file correctly.
To be more precise:
// Temporary object is not yet created here
if (std::ifstream("file.txt"))
{
// Temporary object is already destroyed here
std::cout << "File present\n";
}
// Or here
From documentation:
(destructor)[virtual] (implicitly declared)
destructs the basic_ifstream and the associated buffer, closes the file