Home  >  Article  >  Backend Development  >  How to create a directory in golang

How to create a directory in golang

angryTom
angryTomOriginal
2020-03-14 15:10:0212546browse

How to create a directory in golang

How to create a directory in golang

The operations on directories and file names in golang are all in the os package. The specific directory creation is It is implemented through the two functions Mkdir and MkdirAll. The usage of these two functions is the same.

os.Mkdir(dirName string, perm FileMode)

1. dirName is the directory (folder path) to be created. , can be an absolute path or a relative path (relative to GOPATH)

2. perm represents the permissions of the created directory, such as 0777 (the read r permission value is 4, the write permission w value is 2, execute The authority Examples are as follows:

package main
 
import (
   "os"
   "fmt"
)
 
func main() {
   err := os.Mkdir("/data/program/goapp/golang", 0666)
   if err != nil {
      fmt.Println(err)
   }
}

The difference between Mkdir and MkdirAll

1. When Mkdir creates a directory, its parent directory must exist, otherwise the creation will fail

2. MkdirAll can create directories recursively, that is, as long as the root directory exists, as follows:

err := os.MkdirAll("/data/program/goapp/golang/test/hello", 0766)
if err != nil {
   fmt.Println(err)
}
In this example: /data/program/goapp is an existing directory, and the subdirectory golang/test /hello does not exist. At this time, you need to use MkdirAll to create the

PHP Chinese website, a large number of programming tutorials and

website construction tutorials

, welcome to learn!

The above is the detailed content of How to create a directory in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn