do I need to close a std::fstream? [duplicate]

I think the previous answers are misleading.

fstream is a proper RAII object, it does close automatically at the end of the scope, and there is absolutely no need whatsoever to call close manually when closing at the end of the scope is sufficient.

In particular, it’s not a “best practice” and it’s not necessary to flush the output.

And while Drakosha is right that calling close gives you the possibility to check the fail bit of the stream, nobody does that, anyway.

In an ideal world, one would simply call stream.exceptions(ios::failbit) beforehand and handle the exception that is thrown in an fstream’s destructor. But unfortunately exceptions in destructors are a broken concept in C++ so that’s not a good idea.

So if you want to check the success of closing a file, do it manually (but only then).

Leave a Comment