Golang Determining whether *File points to file or directory

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
}

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

Tags:

File

Go