Reputation: 17486
I read a question from a book that said "If the OS closes a file after the program terminates, why does the programmer need to close a file manually (i.e. call file.close()
)?"
The only reason I could come up with is that the program may not terminate correctly, and so the file may be still open, therefore consuming system resources, because the file is kept on a buffer.
Are there any other reasons?
EDIT: I thought of another reason. Calling file.close()
obliges the OS to flush to disk any changes that haven't been committed to the file.
Upvotes: 0
Views: 1595
Reputation: 4369
In some situations the program will call open so many times that it'll run out of file descriptors if they aren't released again.
Upvotes: 1
Reputation: 68
If the programmer manually closes the file they have control over when/how the resources are released.
If it is left to the OS you cant be sure of when/if clean-up will take place, its generally bad practice as well.
Upvotes: 1