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.3k Golang : Command line ticker to show work in progress
+12.2k Golang : Exit, terminating or aborting a program
+8.2k Golang : Ackermann function example
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+5.5k Golang : Error handling methods
+14.1k Golang : How to filter a map's elements for faster lookup
+13.9k Golang : Get uploaded file name or access uploaded files
+11.3k Golang : Simple file scaning and remove virus example
+6.9k Golang : Gorrila mux.Vars() function example
+10.8k Golang : Read until certain character to break for loop
+8.1k Your page has meta tags in the body instead of the head
+5k Javascript : Change page title to get viewer attention