Menu Close

Go – How to create directory in go

Here, We will see How to create directory in go. We can do it by using Mkdir() function in os package in go golang.

Function prototype:

func Mkdir(dir string, perm FileMode) error

Input Parameter:
dir : directory name
perm: Unix permission bit

If you give only directory name then it 
will in create directory in current working 
directory.

If you give directory name with path like 
/User/john/directory_name then it will create 
directory in "/User/john/" path.

Return value:

Mkdir() function in os package creates
new directory with the specified name and 
permission bits (before umask)

If there is an error, it will be of 
type *PathError.

Example with code:

package main

import (
  "fmt"
  "os"
)

func main() {


  err := os.Mkdir("godir", 0755)

  if err != nil {

    fmt.Println(err)

  }
}

Output:

godir
package main

import (
  "fmt"
  "os"
)

func main() {


  err := os.Mkdir("/User/john/godir", 0755)

  if err != nil {

    fmt.Println(err)

  }
}

Output:

C02YX14CLVDD:src $ ls
godir sample sample.go

C02YX14CLVDD:src $ pwd
/Users/john

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, os, packages

Leave a Reply

Your email address will not be published. Required fields are marked *