Golang : Check if directory exist and create if does not exist
Anyway, need to modify an existing Golang program for a friend. The original developer left her company and basically, she needs the program to check if a directory/folder exist or not. If it is not there, create the folder and also need to report if and why the directory creation failed.
Below is a function that should check if a directory exists and create one if it does not exist.
Here you go!
package main
import (
"fmt"
"os"
)
func createDirectory(dirName string) bool {
src, err := os.Stat(dirName)
if os.IsNotExist(err) {
errDir := os.MkdirAll(dirName, 0755)
if errDir != nil {
panic(err)
}
return true
}
if src.Mode().IsRegular() {
fmt.Println(dirName, "already exist as a file!")
return false
}
return false
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage : %s <directory>\n", os.Args[0])
os.Exit(0)
}
directory := os.Args[1]
result := createDirectory(directory)
fmt.Println(directory, "created : ", result)
}
Sample output:
$ ./createdirifnotexist
Usage : ./createdirifnotexist
$ ./createdirifnotexist webserver
webserver already exist as a file!
webserver created : false
$ ./createdirifnotexist webserver2
webserver2 created : true
$ ./createdirifnotexist webserver2
webserver2 created : false
$ rm -rf webserver2
$ ./createdirifnotexist webserver2
webserver2 created : true
Happy coding!
References:
https://golang.org/pkg/os/#IsNotExist
https://www.socketloop.com/tutorials/golang-check-if-a-directory-exist-in-go
See also : Golang : Determine if directory is empty with os.File.Readdir() function
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
+13.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+3.7k Javascript : How to loop over and parse JSON data?
+8.7k Golang : Read until certain character to break for loop
+5.9k Golang : Scan files for certain pattern and rename part of the files
+8.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+7.6k Golang : Flip coin example
+10.7k Golang : Query string with space symbol %20 in between
+16.7k Golang : Clearing slice
+10.3k Golang : Validate email address
+4k Golang : Launching your executable inside a console under Linux
+8.3k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+27.5k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions