Search code examples
c++fstreamifstream

Should I close a file when it wasn't able open?


Should I close a file when it wasn't able to open?

Should I write this:

std::ifstream file(DATA_PATH);
if (!file.good()) //File doesn't exist
{
    //do something
}
else //file exists
{
    //do something
    file.close();
}

Or should I write:

std::ifstream file(DATA_PATH);
if (!file.good()) //File doesn't exist
{
    //do something
}
else //file exists
{
    //do something
}
file.close();

Solution

  • No, that's not necessary to be done explicitly. (File) streams are closed when going out of scope implicitly always.

    The close() function of a std::iostream() also is an idempotent operation, and never will harm the streams state beyond the stream gets closed (or never was successfully opened).