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.
If you write to a file without closing, the data won't make it to the target file.
You've learned why it's important to close files in Python. Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.
In a large program, which runs on long after you have finished reading/writing to the file, not closing it means that your program is still holding the resource. This means that other processes cannot acquire that file until your program terminates (which may not be what you wish for).
▪︎when a file was not closed correctly before the program is terminated normally, the operating system will try to close the file. In many cases this can prevent a data loss. ▪︎when a file was not closed correctly, and the programm is terminated unexpectedly by a crash, the loss of data can hardly be prevented.
It does exactly what cppreference says it will: the failbit will be set, and you can inspect it with the fail() method. For instance, the following prints "fail\n":
#include <iostream>
#include <fstream>
int main(int argc, char ** argv)
{
std::ofstream out;
out.close();
if (out.fail())
std::cout << "fail" << std::endl;
return 0;
}
In terms of interaction with the operating system, there's nothing there to close, but it's otherwise harmless.
From the C++ standard, §27.9.1.4 [filebuf.members], paragraph 6:
basic_filebuf<charT,traits>* close();
Effects: Ifis_open() == false
, returns a null pointer.…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With