c++stdfstreamofstream

do I need to close a std::fstream?


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.


Solution

  • 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, most code doesn’t do this anyway (and while more code should, this doesn’t apply to all code, since there’s often no good way of handling such failures).

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

    (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++, and the fstream destructor will therefore never throw, so this way does’t work here.)