Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 230
David Mnatsakanyan Avatar asked Jan 31 '15 15:01

David Mnatsakanyan


People also ask

What will happen if you don't close an open file?

If in both programs you don't close the file the second program that tries to open the file will crash because the file is used by another program.

What happens if we don't close a file using filename close () in your program?

If you write to a file without closing, the data won't make it to the target file. But after some surfing I got to know that Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

What happens if you dont close stream C#?

If you don't close it, you can't guarantee that it'll write out the last piece of data written to it. This is because it uses a buffer and the buffer is flushed when you close the stream. Second, it will lock the file as open preventing another process from using it.

What happens if you don't close a file in C++?

In a large program, which runs on long after you have finished reading/writing to the file, not closing it means that your program is still holding the resource. This means that other processes cannot acquire that file until your program terminates (which may not be what you wish for). Arshia You are missing the point.


2 Answers

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"; } 
like image 76
juanchopanza Avatar answered Sep 21 '22 00:09

juanchopanza


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)

like image 30
πάντα ῥεῖ Avatar answered Sep 20 '22 00:09

πάντα ῥεῖ