do I need to close a std::fstream?

Tobias Langner picture Tobias Langner · Jan 26, 2011 · Viewed 36.8k times · Source

Possible Duplicate:
Do I need to manually close a ifstream?

Do I need to call fstream.close() or is fstream a proper RAII object that closes the stream on destruction?

I have a local std::ofstream object inside a method. Can I assume that the file is always closed after exiting this method without calling close? I could not find documentation of the destructor.

Answer

Konrad Rudolph picture Konrad Rudolph · Jan 26, 2011

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