Tobias Langner Tobias Langner - 5 months ago 47
C++ Question

do I need to close a std::fstream?

Possible Duplicate:

Do I need to manually close a ifstream?

Do I need to call
or is
a proper RAII object that closes the stream on destruction?

I have a local
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.


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