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
In Golang, we can use the Stat() function in the os package to check if a file exists or not.
os. Stat and os. IsNotExist() can be used to check whether a particular file or directory exist or not.
To create a single directory in Go, use the os. Mkdir() function. If you want to create a hierarchy of folders (nested directories), use os. MkdirAll() .
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:
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With