英文:
When to close a file?
问题
在你只想创建文件时,是否有必要关闭文件?我认为只有在读取或写入的情况下才是必要的。
_, err := os.OpenFile(name, os.O_CREATE, 0640)
英文:
Is necessary to close a file when you only want create it? I'm supposed that it's only necessary in case of reading or writing.
_, err := os.OpenFile(name, os.O_CREATE, 0640)
答案1
得分: 4
会有效吗?是的。文件将被创建。
你应该这样做吗?不。尽管有时候你可以逃脱,但总的来说这是个坏主意。
打开一个文件会分配资源,比如给你的进程分配一个文件句柄。你应该关闭它以释放这些资源。否则,这些资源将在进程结束之前不可用。
英文:
Will it work? Yes. The file will be created.
Should you do it? No. It is a bad idea in general even though you can get away with it sometimes.
Opening a file allocates resources like a file handle to your process. You should close it to free those resources. Otherwise they will be unavailable until the process dies.
答案2
得分: 1
当你创建文件时,同时也打开了它,所以你应该关闭它。
英文:
When you create the file you also open it, so you should close it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论