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
+6.1k Golang : Compound interest over time example
+12.5k Golang : Encrypt and decrypt data with x509 crypto
+18.1k Golang : Get all upper case or lower case characters from string example
+11k Golang : Removes punctuation or defined delimiter from the user's input
+11.6k Use systeminfo to find out installed Windows Hotfix(s) or updates
+10.4k Golang : How to check if a website is served via HTTPS
+13.4k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+22.4k Golang : Convert seconds to minutes and remainder seconds
+14.7k Golang : Convert(cast) int to float example
+17.2k Golang : Get input from keyboard
+22.8k Generate checksum for a file in Go
+10.8k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example