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 : Format strings to SEO friendly URL example
+15.3k Golang : rune literal not terminated error
+8.6k Golang : Gorilla web tool kit schema example
+15.5k Golang : Get current time from the Internet time server(ntp) example
+12.2k Elastic Search : Return all records (higher than default 10)
+8.8k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+16.2k CodeIgniter/PHP : Create directory if does not exist example
+13.9k Golang : Chunk split or divide a string into smaller chunk example
+13.6k Golang : Gin framework accept query string by post request example
+14.8k Golang : How do I get the local IP (non-loopback) address ?
+5.1k Python : Convert(cast) string to bytes example
+6.7k Golang : How to setup a disk space used monitoring service with Telegram bot