Maria Ines Parnisari
Maria Ines Parnisari

Reputation: 17486

Why is it necessary to close a file after using it?

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

Answers (2)

mzedeler
mzedeler

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

Neil Surridge
Neil Surridge

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

Related Questions