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 How to show different content from website server when AdBlock is detected?
+7.5k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+7.7k Golang : Set or add headers for many or different handlers
+18.1k Golang : Execute shell command
+5.5k Golang : Convert an executable file into []byte example
+14k Golang : Find location by IP address and display with Google Map
+14.8k Golang : Generate universally unique identifier(UUID) example
+18.4k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+5.1k Golang : Calculate US Dollar Index (DXY)
+9.7k Golang : Fix go.exe is not compatible with the version of Windows you're running
+29.3k Golang : How to redirect to new page with net/http?
+6.9k Golang Hello World Example