Golang Determining whether *File points to file or directory
For example,
package main
import (
"fmt"
"os"
)
func main() {
name := "FileOrDir"
fi, err := os.Stat(name)
if err != nil {
fmt.Println(err)
return
}
switch mode := fi.Mode(); {
case mode.IsDir():
// do directory stuff
fmt.Println("directory")
case mode.IsRegular():
// do file stuff
fmt.Println("file")
}
}
Note:
The example is for Go 1.1. For Go 1.0, replace case mode.IsRegular():
with case mode&os.ModeType == 0:
.
Here is another possibility:
import "os"
func IsDirectory(path string) (bool, error) {
fileInfo, err := os.Stat(path)
if err != nil{
return false, err
}
return fileInfo.IsDir(), err
}
Here is how to do the test in one line:
if info, err := os.Stat(path); err == nil && info.IsDir() {
...
}
import "os"
// FileExists reports whether the named file exists as a boolean
func FileExists(name string) bool {
if fi, err := os.Stat(name); err == nil {
if fi.Mode().IsRegular() {
return true
}
}
return false
}
// DirExists reports whether the dir exists as a boolean
func DirExists(name string) bool {
if fi, err := os.Stat(name); err == nil {
if fi.Mode().IsDir() {
return true
}
}
return false
}
fileOrDir, err := os.Open(name)
if err != nil {
....
}
info, err := fileOrDir.Stat()
if err != nil {
....
}
if info.IsDir() {
....
} else {
...
}
Be careful to not open and stat the file by name. This will produce a race condition with potential security implications.
If your open succeeds then your have a valid file handle and you should use the Stat() method on it to obtain the stat. The top answer is risky because they suggest to call os.Stat() first and then presumably os.Open() but someone could change the file in between the two calls.