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?
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With