I am trying to work out if I need to call close on a fstream object if the intial open failed.
i.e.
std::fstream strm;
strm.open( "filename" );
if( ! strm.fail() )
{
// Do something
strm.close(); // [1]
}
strm.close(); // [2]
Where should close be called here - should it always be called [2] or only if the open succeeds[1]?
I may be going over the top here, but coming from the Windows API way of typically doing this I have CloseHandle( ... ); embedded in my mind :-)
The stream will be automatically closed by the fstream's destructor - there is no need to close it explicitly, unless your program logic demands it, for example if you are going to re-open it. However, closing a stream that didn't open won't cause any problems.