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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
ofstreamwill 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:https://cplusplus.com/reference/fstream/ofstream/close/