impulse impulse - 15 days ago 5
C++ Question

std::ifstream initialization with filename

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;
}


Since I am not using any object for
std::ifstream
, how do I close the file? Or is it not required to call close?

Answer

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

Comments