Golang : Check to see if *File is a file or directory
Sometimes, we need to write codes that is robust and flexible enough to handle different situation. For example, if a program is going to open up a directory or file. In this simple tutorial, we will learn how to handle the situation when opening up a file or directory with os.Open()
function. We will use the FileInfo.Mode()
function to determine if the object that we opened is a file or directory.
package main
import (
"os"
"fmt"
)
func main() {
object := "./FileDir" // this could be file or directory
fdir, err := os.Open(object)
if err != nil {
fmt.Println(err)
return
}
defer fdir.Close()
finfo, err := fdir.Stat()
if err != nil {
fmt.Println(err)
return
}
switch mode := finfo.Mode(); {
case mode.IsDir():
fmt.Println("object is a directory")
case mode.IsRegular():
fmt.Println("object is a file")
}
}
Hope this tutorial can be useful to you. Remember to check out the SEE ALSO below.
Reference :
See also : Golang : Read directory content with os.Open
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.5k Golang : How to execute code at certain day, hour and minute?
+3.5k Java : Random alphabets, alpha-numeric or numbers only string generator
+16.1k CodeIgniter/PHP : Create directory if does not exist example
+20.8k Golang : Get password from console input without echo or masked
+10.2k Generate Random number with math/rand in Go
+12.3k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+17.1k Golang : Multi threading or run two processes or more example
+7.2k Golang : Rot13 and Rot5 algorithms example
+13.6k Golang : convert(cast) string to float value
+14.2k Golang : GUI with Qt and OpenCV to capture image from camera
+11.9k Golang : Simple client-server HMAC authentication without SSL example
+6.8k Restart Apache or Nginx web server without password prompt