If I have a std::ofstream
that may or may not have been opened, is it safe to try to close
regardless? In otherwords does close()
do anything nasty (throw exception, etc) if !is_open()
. For example
std::ofstream out;
if (some_condition)
{
out.open(path, std::ios::out);
}
After I'm done with the file, can I just say
out.close();
Or should I first check
if (out.is_open())
out.close();
The only description of std::basic_fstream::close
on cppreference is
Closes the associated file.
Effectively callsrdbuf()->close()
. If an error occurs during operation,setstate(failbit)
is called.