是否有必要在阅读(仅)任何编程语言后关闭文件? [英] Is it necessary to close files after reading (only) in any programming language?

查看:42
本文介绍了是否有必要在阅读(仅)任何编程语言后关闭文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到程序应该在写入文件后关闭文件,以防写入缓冲区中仍有数据尚未物理写入.我还看到一些语言(例如 Python)会自动关闭所有超出范围的文件,例如程序结束时.

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.)

推荐答案

一般来说,在使用完文件后,您应该始终关闭它.

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

原因 1: 没有无限可用的文件描述符(或在 Windows 中,概念上类似的 HANDLES).每次访问文件资源时,即使是为了读取,也会减少可供其他进程使用的句柄(或 FD)的数量.每次关闭句柄时,都会释放它并使其可用于其他进程.

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

原因 2:如果您正在执行除读取文件之外的任何其他操作,那么如果多个进程或线程访问同一个文件,则存在竞争条件问题.为避免这种情况,您可能会发现文件锁已就位.http://en.wikipedia.org/wiki/File_locking

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..

原因 3: 绝对没有理由不关闭文件.在任何语言中,这就是为什么 Python 帮助懒惰的程序员,并自动关闭超出范围的句柄,以防程序员忘记.

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.

这篇关于是否有必要在阅读(仅)任何编程语言后关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆