C++打开的文件一定要用close()方法关闭

通过前面的学习我们知道,C++ 使用 open() 方法打开文件,使用 close() 方法关闭文件。例如(程序一):

#include <iostream>     //std::cout
#include <fstream>        //std::ofstream
using namespace std;
int main()
{
    const char * url = "http://c.biancheng.net/cplus/";
    //以文本模式打开out.txt
    ofstream destFile("out.txt", ios::out);
    if (!destFile) {
        cout << "文件打开失败" << endl;
        return 0;
    }
    //向out.txt文件中写入 url 字符串
    destFile << url;
    //关闭打开的 out.txt 文件
    destFile.close();
    return 0;
}

执行该程序,会生成一个 out.txt 文件,内部存有如下内容:

http://c.biancheng.net/cplus/
posted @ 2022-08-19 22:46  luoganttcc  阅读(224)  评论(0)    收藏  举报