Why should I close a file?
Hi,
I building an app that write info to a file every few seconds using:
Code:
std::wofstream FileWrite
At the moment I am closing the file after writing each info message,
And I was wondering if I am the only one who is writing to the file why should i close it?
Can I leave a file open during the application life time?
Regards
Re: Why should I close a file?
No reason why not. Probably better to do so, actually.
Re: Why should I close a file?
Thats what everyone say, but I still can't get a clear answer explaining why not.
Re: Why should I close a file?
Quote:
Originally Posted by PeterRoddis
Thats what everyone say, but I still can't get a clear answer explaining why not.
That's because there is no reason why not.
Re: Why should I close a file?
Quote:
Originally Posted by PeterRoddis
Hi,
I building an app that write info to a file every few seconds using:
Code:
std::wofstream FileWrite
At the moment I am closing the file after writing each info message,
And I was wondering if I am the only one who is writing to the file why should i close it?
Can I leave a file open during the application life time?
Regards
I think there is at least one good reason to close the file: If the app crashes, you don't loose any data which may be hanging around in the output buffer.
A smaller concern is the general rule of not holding on to resources unnecessarily.
Re: Why should I close a file?
Quote:
Originally Posted by Zaccheus
I think there is at least one good reason to close the file: If the app crashes, you don't loose any data which may be hanging around in the output buffer.
A smaller concern is the general rule of not holding on to resources unnecessarily.
I thought that flushing the buffer would solve this issue.
Re: Why should I close a file?
Quote:
Originally Posted by PeterRoddis
I thought that flushing the buffer would solve this issue.
It would.
Re: Why should I close a file?
Hi PeterRoddis,
one reason I can think of is when you want to associate the same fstream object with another file.
Code:
fstream fout;
fout.open("abc.txt"); // ok
fout.open("def.txt") // Error. fstream object must be closed to open a new file
was this so obvious that it was uncessary for me to even bring it up??
sorry I'm still learning.
Re: Why should I close a file?
Quote:
Originally Posted by potatoCode
Hi PeterRoddis,
one reason I can think of is when you want to associate the same fstream object with another file.
Code:
fstream fout;
fout.open("abc.txt"); // ok
fout.open("def.txt") // Error. fstream object must be closed to open a new file
was this so obvious that it was uncessary for me to even bring it up??
sorry I'm still learning.
It is a good point 8-)