为什么在 Go 中写入被删除的文件时不会引发错误?
时间:2024-02-17
浏览:342
作者:佚名
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《为什么在 Go 中写入被删除的文件时不会引发错误?》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
问题内容
即使该程序正在写入已删除的文件,它仍能成功运行。为什么这有效?
package main
import (
"fmt"
"os"
)
func main() {
const path = "test.txt"
f, err := os.Create(path) // Create file
if err != nil {
panic(err)
}
err = os.Remove(path) // Delete file
if err != nil {
panic(err)
}
_, err = f.WriteString("test") // Write to deleted file
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
fmt.Printf("No errors occurred") // test.txt doesn't exist anymore
}解决方案
在类 unix 系统上,当进程打开文件时,它会获取 File descriptor,该值指向进程 文件表 条目,而该条目又引用磁盘上的 inode structure。 inode保存文件信息,包括数据位置。
目录的内容只是 inode 编号和名称对。
如果删除文件,只需从目录中删除到 inode 的链接,inode 仍然存在(只要没有从某个地方到它的链接,包括进程)并且可以从 data 读取和写入数据位置。
在 windows 上,此代码会失败,因为 windows 不允许删除打开的文件:
panic: remove test.txt: The process cannot access the file because it is being used by another process. goroutine 1 [running]: main.main() D:/tmp/main.go:18 +0x1d1 exit status 2
理论要掌握,实操不能落!以上关于《为什么在 Go 中写入被删除的文件时不会引发错误?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
热门专题
