V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
wtfedc
V2EX  ›  问与答

golang 创建多级目录失败

  •  
  •   wtfedc · 2022-09-17 14:25:11 +08:00 · 1014 次点击
    这是一个创建于 577 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请教个问题,没搜到类似情况的。

    调用 os.Create 或者 os.WriteFile ,文件名是一个绝对路径,调用前 后边几级目录还没创建,按官方的例子,会自动创建目录,实际使用会报错: no such file or directory

    调用前加了syscall.Umask(0),对新创建文件的权限,取消了掩码限制

    绝对路径类似于 /Users/admin/xxx/blog/content/zh-CN/post/filedir/test

    已有目录 /Users/admin/xxx/blog/content/zh-CN/post 的权限也是 3 个 rwx ,自己在 shell 操作创建也是没问题。

    因为拼接的路径,后边几级目录不确定,不至于每次创建一级,就调用个 os.Chmod 吧。。。


    官方文档 func WriteFile(name string, data []byte, perm FileMode) error

    WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions.

    err := os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)
    if err != nil {
    log.Fatal(err)
    }
    
    7 条回复    2022-09-17 14:47:34 +08:00
    keepeye
        1
    keepeye  
       2022-09-17 14:28:46 +08:00
    只会自动创建文件吧,目录需要你自己创建或者 os.MkdirAll
    wtfedc
        2
    wtfedc  
    OP
       2022-09-17 14:34:49 +08:00
    @keepeye 下边的代码是官方例子,我也调不通,不确定是不是和 macOS 有关系
    wtfedc
        3
    wtfedc  
    OP
       2022-09-17 14:40:21 +08:00
    @keepeye 在 windows 也跑了一下,同样报错。可能我理解错了,不能使用 WriteFile 创建文件夹。官方给的个例子真的不怎么好,一个跑不通的例子,算了,转身去用 MkdirAll 了
    keepeye
        4
    keepeye  
       2022-09-17 14:41:34 +08:00
    官方的例子让你知道不会帮你创建目录,你点下 run 就知道了啊,create file 不是 create dir
    keepeye
        5
    keepeye  
       2022-09-17 14:44:11 +08:00   ❤️ 1
    你再点开 WriteFile 源码,所谓的自动创建文件就是 open 操作的时候使用了 O_CREAT mode

    OpenFile(name, O_WRONLY|O_CREATE|O_TRUNC, perm)
    keepeye
        6
    keepeye  
       2022-09-17 14:46:06 +08:00
    可以参考下 touch 命令,也会报同样的错误

    touch: cannot touch 'a/b.txt': No such file or directory
    wtfedc
        7
    wtfedc  
    OP
       2022-09-17 14:47:34 +08:00
    @keepeye 感谢,了解了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1455 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 17:18 · PVG 01:18 · LAX 10:18 · JFK 13:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.