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
+14.4k Golang : Rename directory
+12k Golang : Detect user location with HTML5 geo-location
+24.9k Golang : Create PDF file from HTML file
+8.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+5.5k Golang : Shortening import identifier
+16.2k Golang : How to extract links from web page ?
+14.7k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+5.5k PHP : Fix Call to undefined function curl_init() error
+10.2k Golang : How to check if a website is served via HTTPS
+16.1k Golang : Loop each day of the current month example
+6k PageSpeed : Clear or flush cache on web server
+7.6k Golang : get the current working directory of a running program