Golang : Check if a directory exist or not
In this short tutorial, we will learn how to check if a parameter passed as argument is directory or not. It is pretty straight forward by using the os.Stat.IsDir() function
checkdir.go
package main
import (
"os"
"flag"
"fmt"
)
func main() {
flag.Parse() // get the arguments from command line
source_dir := flag.Arg(0) // get the source directory from 1st argument
fmt.Println("Source :" + source_dir)
// check if the source dir exist
src, err := os.Stat(source_dir)
if err != nil {
panic(err)
}
// check if the source is indeed a directory or not
if !src.IsDir() {
fmt.Println("Source is not a directory")
os.Exit(1)
}
}
Hope this will be helpful.
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
+8.9k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+8.7k Golang : convert(cast) string to integer value
+13.3k Golang : dial tcp: too many colons in address
+5.3k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+8.4k Golang : Get query string value on a POST request
+10.5k Golang : How to reverse slice or array elements order
+31.9k Golang : Unmarshal JSON from http response
+4.6k Gogland : Single File versus Go Application Run Configurations
+3.4k Golang : Qt splash screen with delay example
+3.5k Golang : Generate Codabar
+18k Golang : How to create new XML file ?
+6k Golang : Transform comma separated string to slice example