What happens if I never call `close` on an open file stream? [duplicate]

狂风中的少年 提交于 2019-12-03 09:54:01

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

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";
}

To fortify juanchopanza's answer with some reference from the std::fstream documentation

(destructor)
[virtual](implicitly declared)

destructs the basic_fstream and the associated buffer, closes the file (virtual public member function)

In this case, nothing will happen and code execution time is very less.

However, if your codes runs for long time when you are continuously opening files and not closing, after a certain time, there may be crash in run time.

when you open a file, the operating system creates an entry to represent that file and store the information about that opened file. So if there are 100 files opened in your OS then there will be 100 entries in OS (somewhere in kernel). These entries are represented by integers like (...100, 101, 102....). This entry number is the file descriptor. So it is just an integer number that uniquely represents an opened file in operating system. If your process open 10 files then your Process table will have 10 entries for file descriptors.

Also, this is why you can run out of file descriptors, if you open lots of files at once. Which will prevent *nix systems from running, since they open descriptors to stuff in /proc all the time.

Similar thing should happen in case of all operating system.

Under normal conditions there is no difference.

BUT under exceptional conditions (with slight change) the call to close can cause an expception.

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