Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

readfile - Is it necessary to close files after reading (only) in any programming language?

I read that a program should close files after writing to them in case there is still data in the write buffer not yet physically written to it. I also read that some languages such as Python automatically close all files that go out of scope, such as when the program ends.

But if I'm merely reading a file and not modifying it in any way, maybe except the OS changing its last-access date, is there ever a need to close it (even if the program never terminates, such as a daemon that monitors a log file)?

(Why is it necessary to close a file after using it? asks about file access in general, not only for reading.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general, you should always close a file after you are done using it.

Reason number 1: There are not unlimited available File Descriptors (or in windows, the conceptually similar HANDLES). Every time you access a file ressource, even for reading, you are reducing the number of handles (or FD's) available to other processes. every time you close a handle, you release it and makes it available for other processes.

Now consider the consequences of a loop that opens a file, reads it, but doesn't close it...

http://en.wikipedia.org/wiki/File_descriptor

https://msdn.microsoft.com/en-us/library/windows/desktop/aa364225%28v=vs.85%29.aspx

Reason number 2: If you are doing anything else than reading a file, there are problems with race conditions, if multiple processes or threads accesses the same file.. To avoid this, you may find file locks in place. http://en.wikipedia.org/wiki/File_locking

if you are reading a file, and not closing it afterward, other applications, that could try to obtain a file lock are denied access.

oh - and the file can't be deleted by anyone that doesn't have rights to kill your process..

Reason number 3: There is absolutely no reason to leave a file unclosed. In any language, which is why Python helps the lazy programmers, and automatically closes a handle that drops out of scope, in case the programmer forgot.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...