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
+10.7k Golang : convert(cast) float to string
+11.8k Python : Convert IPv6 address to decimal and back to IPv6
+50.2k Golang : Check if item is in slice/array
+5k Fontello : How to load and use fonts?
+11.9k Golang : Qt progress dialog example
+15.1k Golang :Trim white spaces from a string
+27.9k Golang : How to create new XML file ?
+13.3k Golang : GUI with Qt and OpenCV to capture image from camera
+11.5k Golang : "https://" not allowed in import path
+4.9k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+4.1k Golang : micron to centimeter example