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

David Mnatsakanyan picture David Mnatsakanyan · Jan 31, 2015 · Viewed 10.9k times · Source

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

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

Answer

juanchopanza picture juanchopanza · Jan 31, 2015

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