Does ofstream close its files automatically? [dupl

2019-04-06 03:56发布

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?

标签: c++ ofstream
2条回答
你好瞎i
2楼-- · 2019-04-06 04:34

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.

查看更多
甜甜的少女心
3楼-- · 2019-04-06 04: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/

查看更多
登录 后发表回答