16

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?

Community
  • 1
  • 1
nhtrnm
  • 1,411
  • 3
  • 15
  • 24
  • see this question http://stackoverflow.com/questions/4802494/do-i-need-to-close-a-stdfstream (and even that one is a duplicate) – Dirk Oct 15 '12 at 16:37
  • 1
    @Dirk I just looked for ofstream not ifstream, I'll be searching broadly next next time. Close my question if you wish. – nhtrnm Oct 15 '12 at 16:41

2 Answers2

35

ofstream will close files when its destructor is called, i.e. when it goes out of scope. However, calling close() 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 the failbit:

http://www.cplusplus.com/reference/iostream/ofstream/close/

Benj
  • 31,668
  • 17
  • 78
  • 127
8

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.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203