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

后端 未结 3 1752
遇见更好的自我
遇见更好的自我 2020-12-11 10:12

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 langua

3条回答
  •  爱一瞬间的悲伤
    2020-12-11 11:08

    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.

提交回复
热议问题