Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Determining whether *File points to file or directory

Tags:

file

go

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 
like image 913
NominSim Avatar asked Jan 11 '12 18:01

NominSim


People also ask

How do you check if a file is created in Golang?

In Golang, we can use the Stat() function in the os package to check if a file exists or not.

How do I find my Golang path?

os. Stat and os. IsNotExist() can be used to check whether a particular file or directory exist or not.

How do I create a folder in Golang?

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() .


1 Answers

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:.

like image 100
peterSO Avatar answered Oct 01 '22 05:10

peterSO