写入不存在的文件会报错吗?

huangapple go评论70阅读模式
英文:

Write to non existing file gives no error?

问题

为什么如果在写入之前删除文件,f.Write() 不会返回任何错误?

package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	f, err := os.Create("foo")
	if err != nil {
		panic(err)
	}

	if err := os.Remove("foo"); err != nil {
		panic(err)
	}

	if _, err := f.Write([]byte("hello")); err != nil {
		panic(err) // would expect panic here
	}

	fmt.Println("no panic?")
}

在这段代码中,如果在写入之前删除文件,f.Write() 不会返回任何错误。这是因为在调用 f.Write() 时,文件已经被打开并且文件描述符已经被分配给了变量 f。即使文件在写入之前被删除,文件描述符仍然存在,并且可以继续写入数据。只有在关闭文件之后,再次尝试写入时才会返回错误。因此,即使删除了文件,f.Write() 仍然可以成功执行而不会引发错误。

英文:

Why would f.Write() not return any error if I remove the file before I write?

package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	f, err := os.Create("foo")
	if err != nil {
		panic(err)
	}

	if err := os.Remove("foo"); err != nil {
		panic(err)
	}

	if _, err := f.Write([]byte("hello")); err != nil {
		panic(err) // would expect panic here
	}

	fmt.Println("no panic?")
}

http://play.golang.org/p/0QllIB6L9O

答案1

得分: 1

显然这是可以预料的。

当你删除一个文件时,实际上是删除了对该文件(inode)的链接。如果有人已经打开了该文件,他们将保留他们所拥有的文件描述符。文件仍然存在于磁盘上,占用空间,并且如果你有权限,可以对其进行写入和读取。

来源:https://unix.stackexchange.com/questions/146929/how-can-a-log-program-continue-to-log-to-a-deleted-file

英文:

Apparently this is expected.

> When you delete a file you really remove a link to the file (to the inode). If someone already has that file open, they get to keep the file descriptor they have. The file remains on disk, taking up space, and can be written to and read from if you have access to it.

Source: https://unix.stackexchange.com/questions/146929/how-can-a-log-program-continue-to-log-to-a-deleted-file

huangapple
  • 本文由 发表于 2015年12月17日 09:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/34325128.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定