为了账号安全,请及时绑定邮箱和手机立即绑定

为什么写入已删除的文件不会在 Go 中返回错误?

为什么写入已删除的文件不会在 Go 中返回错误?

Go
慕的地6264312 2022-06-27 10:38:38
即使它正在写入已删除的文件,该程序也会成功运行。为什么这行得通?package mainimport (    "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}
查看完整描述

1 回答

?
大话西游666

TA贡献1817条经验 获得超14个赞

在类 Unix 系统上,当一个进程打开一个文件时,它会得到一个File descriptor指向进程File table入口的文件,而进程入口又是指磁盘上的inode 结构。inode保存文件信息,包括data location.


目录的内容只是成对的 inode 编号和名称。


如果你删除一个文件,你只需inode从目录中删除一个链接,它inode仍然存在(只要没有从某个地方指向它的链接,包括进程)并且可以从/到读取和写入数据data location。


在 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


查看完整回答
反对 回复 2022-06-27
  • 1 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号