C++ 如果我从未对打开的文件流调用“close”,会发生什么?

C++ 如果我从未对打开的文件流调用“close”,会发生什么?,c++,file,filestreams,C++,File,Filestreams,下面是相同情况下的代码 #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; } #包括 #包括

下面是相同情况下的代码

#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;
}
#包括
#包括
使用名称空间std;
int main(){
流文件;
myfile.open(“example.txt”);

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

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

#include <fstream>

int main()
{
  std::ofstream myfile("example.txt");
  myfile << "Writing this to a file.\n";
}
#包括
int main()
{
std::ofstreammyfile(“example.txt”);

myfile通过引用

(析构函数)
[虚拟](隐式声明)

销毁基本流和相关缓冲区,关闭文件 (虚拟公共成员功能)


在这种情况下,不会发生任何事情,代码执行时间也非常少

但是,如果在连续打开文件而不关闭文件时代码运行很长时间,则在一段时间后,运行时可能会崩溃

当您打开一个文件时,操作系统会创建一个条目来表示该文件并存储有关该打开文件的信息。因此,如果在您的操作系统中打开了100个文件,那么在操作系统中(内核中的某个位置)将有100个条目。这些条目由类似(…100、101、102…)的整数表示。此条目号是文件描述符。因此,它只是一个整数,唯一地表示操作系统中打开的文件。如果您的进程打开了10个文件,则您的进程表将有10个文件描述符条目

此外,这也是如果一次打开大量文件,文件描述符可能会用完的原因。这将阻止*nix系统运行,因为它们总是打开描述符来填充/proc


在所有操作系统中都会发生类似的情况。

在正常情况下没有区别

但是在异常情况下(稍有变化),调用close可能会导致异常

int main()
{
    try
    {
        ofstream myfile;
        myfile.exceptions(std::ios::failbit | std::ios::badbit);
        myfile.open("example.txt");

        myfile << "Writing this to a file.\n";


        // If you call close this could potentially cause an exception
        myfile.close();


        // On the other hand. If you let the destructor call the close()
        // method. Then the destructor will catch and discard (eat) the
        // exception.
    }
    catch(...)
    {
        // If you call close(). There is a potential to get here.
        // If you let the destructor call close then the there is
        // no chance of getting here.
    }
}
intmain()
{
尝试
{
流文件;
异常(std::ios::failbit | std::ios::badbit);
myfile.open(“example.txt”);

myfile它不会阻止整个系统运行,应用程序将无法打开更多文件。它可能会阻止整个应用程序运行。另外,请注意,Windows不使用整数作为文件描述符,也不将其称为文件描述符。实际上,在UNIX/POSIX兼容的操作系统上,打开10个文件将导致此过程FD表包含13个条目:10个用于我们打开的文件,3个用于标准流:
stdin
stdout
stderr
。析构函数关闭文件,没有关于文件描述符的问题。-1甚至
std::ofstream(“example.txt”)您可能会发现这个问题也回答了您的问题:。