Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 318
giladk Avatar asked Jan 22 '19 20:01

giladk


1 Answers

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).

like image 87
πάντα ῥεῖ Avatar answered Oct 10 '22 03:10

πάντα ῥεῖ