In this example, we demonstrate how to create a single directory or multiple directories in Golang with an example.
Go - create a directory with os.Mkdir
The os.Mkdir creates a new directory with the specified name and permission bits.
The example creates a directory named demo. The 0755 means read and execute access for everyone and also write access for the owner of the file.
package main
import (
"log"
"os"
)
func main() {
path := "demo"
err := os.Mkdir(path, 0755)
if err != nil {
log.Fatal(err)
}
}
Output:
G:\GoLang\examples>go run go_example.go
Go create multiple directories with os.MkdirAll
The MkdirAll function creates a directory, along with any necessary parents, and returns nil, or else returns an error. The permission bits are used for all directories that the function creates. If the directory already exists, MkdirAll does nothing and returns nil.
In the example, we create a directory called new along with its parents.
package main
import (
"fmt"
"log"
"os"
)
func main() {
path := "tmp/doc/new"
err := os.MkdirAll(path, 0755)
if err != nil {
log.Fatal(err)
}
fmt.Println("directory created")
}
Output:
G:\GoLang\examples>go run go_example.go directory created
Comments
Post a Comment