mattes
mattes

Reputation: 9429

Write to non existing file gives no error?

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

Upvotes: 3

Views: 307

Answers (1)

mattes
mattes

Reputation: 9429

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

Upvotes: 1

Related Questions