Possible Duplicate:
do I need to close a std::fstream?
int main() {
ofstream a("a.txt");
a << "A" << endl;
//a.close();
}
This works fine, but isn't it necessary to close the file at the end of the program?
Possible Duplicate:
do I need to close a std::fstream?
int main() {
ofstream a("a.txt");
a << "A" << endl;
//a.close();
}
This works fine, but isn't it necessary to close the file at the end of the program?
It is necessary to call close if you want to check the result (success or failure).
Otherwise, the stream's destructor will attempt to close the file for you.
ofstream
will close files when its destructor is called, i.e. when it goes out of scope. However, callingclose()
certainly doesn't do any harm and expresses your intentions to maintenance programmers.Calling
close()
also allows you to check if the close() was successful because you can then also check thefailbit
:http://www.cplusplus.com/reference/iostream/ofstream/close/