如果我从未在打开的文件流上调用`close`会发生什么? [英] What happens if I never call `close` on an open file stream?

查看:79
本文介绍了如果我从未在打开的文件流上调用`close`会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是相同情况的代码.

Below is the code for same case.

#include <iostream>
#include <fstream>

using namespace std;

int main () {
    ofstream myfile;
    myfile.open ("example.txt");
    myfile << "Writing this to a file.\n";
    //myfile.close();
    return 0;
}

如果取消注释myfile.close()行,会有什么区别?

What will be the difference if I uncomment the myfile.close() line?

推荐答案

没有区别.文件流的析构函数将关闭文件.

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

您也可以依靠构造函数打开文件,而不用调用open().您的代码可以简化为:

You can also rely on the constructor to open the file instead of calling open(). Your code can be reduced to this:

#include <fstream>

int main()
{
  std::ofstream myfile("example.txt");
  myfile << "Writing this to a file.\n";
}

这篇关于如果我从未在打开的文件流上调用`close`会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆