亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么寫入已刪除的文件不會在 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 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號