How to create nested directories using Mkdir in Golang?

前端 未结 5 1222
野趣味
野趣味 2021-01-30 15:33

I am trying to create a set of nested directories from a Go executable such as \'dir1/dir2/dir3\'. I have succeeded in creating a single directory with this line:



        
5条回答
  •  别那么骄傲
    2021-01-30 16:05

    This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.

    package main
    
    import (
        "fmt"
        "os"
    )
    
    func main()  {
        if err := ensureDir("/test-dir"); err != nil {
            fmt.Println("Directory creation failed with error: " + err.Error())
            os.Exit(1)
        }
        // Proceed forward
    }
    
    func ensureDir(dirName string) error {
    
        err := os.MkdirAll(dirName, os.ModeDir)
    
        if err == nil || os.IsExist(err) {
            return nil
        } else {
            return err
        }
    }
    

提交回复
热议问题