Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 666
Tobias Langner Avatar asked Jan 26 '11 08:01

Tobias Langner


1 Answers

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

like image 84
Konrad Rudolph Avatar answered Oct 30 '22 09:10

Konrad Rudolph