为什么在使用文件后需要关闭文件? [英] Why is it necessary to close a file after using it?

查看:541
本文介绍了为什么在使用文件后需要关闭文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一本书中读到一个问题,说:如果操作系统在程序终止后关闭文件,为什么程序员需要手动关闭文件(即调用 file.close() code

$ p






$ b $消耗系统资源,因为文件保存在缓冲区中。



是否还有其他原因?

编辑:我想到另外一个原因。调用 file.close()命令操作系统将任何未被提交到文件的更改刷新到磁盘。

解决方案

如果程序员手动关闭文件,他们可以控制何时/如何释放资源。

如果留给操作系统,你无法确定何时/如果清理会发生,通常也是不好的做法。 $ b

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.

解决方案

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.

这篇关于为什么在使用文件后需要关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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