Golang Determining whether *File points to file or directory
FileGoFile Problem Overview
Is there a way to determine whether my *File is pointing to a file or a directory?
fileOrDir, err := os.Open(name)
// How do I know whether I have a file or directory?
I want to be able to read stats about the file if it is just a file, and be able to read the files within the directory if it is a directory
fileOrDir.Readdirnames(0) // If dir
os.Stat(name) // If file
File Solutions
Solution 1 - File
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:
.
Solution 2 - File
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
}
Solution 3 - File
Here is how to do the test in one line:
if info, err := os.Stat(path); err == nil && info.IsDir() {
...
}
Solution 4 - File
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
}
Solution 5 - File
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.