Golang : Check if a directory exist or not
Tags : golang directory
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.
Tags : golang directory
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
+1.7k Unix/Linux/MacOSx : How to remove an environment variable ?
+2k Golang : Combine slices but preserve order example
+15.1k Golang : Display float in 2 decimal points and rounding up or down
+3k Golang : Regular Expression find string example
+1.4k Google : Block or disable caching of your website content
+1.3k Golang : Lock executable to a specific machine with unique hash of the machine
+1.6k Golang : Detect face in uploaded photo like GPlus
+2.3k Golang : Validate credit card example
+19.5k Golang : Marshal and unmarshal json.RawMessage struct example
+18.8k Golang : Generate random string
+4.5k Golang : Generate random integer or float number
+1.8k Golang : Measure execution time for a function