Steven
Steven

Reputation: 2558

Why does writing to a deleted file not return an error in Go?

This program successfully runs even though it's writing to a deleted file. Why does this work?

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
}

Upvotes: 0

Views: 706

Answers (1)

maxim_ge
maxim_ge

Reputation: 1263

On Unix-like systems, when a process opens a file it gets a File descriptor which points to the process File table entry, which, in turn, refers to inode structure on the disk. inode keeps file information, including data location.

Contents of a directory are just pairs of inode numbers and names.

If you delete a file, you simply delete a link to inode from the directory, inode still exists (as long as there is no link to it from somewhere, including processes) and data can be read and written from/to data location.

On Windows this code fails since Windows does not allow opened file to be deleted:

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

Upvotes: 5

Related Questions