Does ofstream close its files automatically? [duplicate]

泄露秘密 提交于 2019-12-12 08:25:00

问题


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?


回答1:


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/




回答2:


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.



来源:https://stackoverflow.com/questions/12900016/does-ofstream-close-its-files-automatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!