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
+33.9k Golang : Get file last modified date and time
+11.5k Golang : How to calculate the distance between two coordinates using Haversine formula
+8.4k Facebook : Getting the friends list with PHP return JSON format
+9.1k Golang : Text file editor (accept input from screen and save to file)
+4.1k Swift : Convert (cast) Float to Int or Int32 value
+18k Golang : Check if directory exist and create if does not exist
+9.4k Golang : ISO8601 Duration Parser example
+13.1k Golang : Recombine chunked files example
+5.5k Golang : Calculate diameter, circumference, area, sphere surface and volume
+5.6k Golang : Calculate pivot points for a cross
+16.1k Golang : How to make a file read only and set it to writable again?
+13.4k Golang : package is not in GOROOT during compilation