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
+21.6k Golang : Strings to lowercase and uppercase example
+15k Golang : How to extract links from web page ?
+16k Golang : How to make a file read only and set it to writable again?
+4.1k Golang : micron to centimeter example
+13.9k Golang : How to get Unix file descriptor for console and file
+4.1k Golang : Display packages names during compilation
+13.2k Golang : How to shuffle elements in array or slice?
+11.7k Generate salted password with OpenSSL example
+3.9k JQuery : Calling a function inside Jquery(document) block
+6.9k Golang : Load DSA public key from file example
+11.7k Golang : http.Get example
+8.6k Golang : Resumable upload to Google Drive(RESTful) example