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
+9.5k Golang : How to profile or log time spend on execution?
+8.3k Golang : Find the length of big.Int variable example
+5.6k Golang : Test input string for unicode example
+6.8k Gogland : Single File versus Go Application Run Configurations
+17.9k Golang : convert int to string
+18.8k Golang : Compare floating-point numbers
+4.2k HTTP common errors and their meaning explained
+4.1k Which content-type(MIME type) to use for JSON data
+4.1k JQuery : Calling a function inside Jquery(document) block
+9.6k Golang : Generate random integer or float number
+18.9k Golang : Check if os.Stdin input data is piped or from terminal
+9.2k Golang : Find and replace data in all files recursively