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();
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With