Search code examples
c++filefilestreams

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


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?


Solution

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