Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ofstream close its files automatically? [duplicate]

Tags:

c++

ofstream

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?

like image 730
nhtrnm Avatar asked Oct 15 '12 16:10

nhtrnm


People also ask

Does C++ automatically close files?

Example# Explicitly closing a file is rarely necessary in C++, as a file stream will automatically close its associated file in its destructor. However, you should try to limit the lifetime of a file stream object, so that it does not keep the file handle open longer than necessary.

Do you need to close ofstream?

So no, we do not need to explicitly call fstream::close() to close the file. After open a file with fstream/ifstream/ofstream, it is safe to throw an exception without manually close the file first.

How do I close an ofstream file?

The close() function is used to close the file currently associated with the object. The close() uses ofstream library to close the file.

What happens if you don't close stream?

There is no difference. The file stream's destructor will close the file.


2 Answers

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.

like image 93
Bo Persson Avatar answered Sep 22 '22 03:09

Bo Persson


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/

like image 21
Benj Avatar answered Sep 23 '22 03:09

Benj