I've spend some time looking for an error in my code and it appeared that at one place I was trying to read contents of a directory like it was the file. Consider the following code:
import (
"fmt"
"os"
)
func init() {
file, err := os.Open("/tmp/")
fmt.Println(file, err) //err == nil here
var b []byte
n, err := file.Read(b)
fmt.Println(n, err) //err == "read /tmp/: is a directory"
}
I am wondering, why os.Open
allows to 'open' a directory without an error if I cannot 'read' it anyway? The documentation says
Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError. [reference]
If the 'directory' is a 'file' is disputable but for me it looks a bit misleading. Is there any usage for that behavior?