douzi2785 2016-02-26 21:21
浏览 48
已采纳

使用os.Stat与os.MkdirAll进行检查

I need to write to a file in a nested directory that may or may not exist.

At first, I checked if the folder existed via os.Stat, doing os.MkdirAll if it doesn't exist, and then opening and writing to a file.

I tried removing the os.Stat and just doing os.MkdirAll, and it appears to work - meaning os.MkdirAll is idempotent.

My question is, is there a benefit of doing the os.Stat check? Is it a much lighter operation than os.MkdirAll?

  • 写回答

1条回答 默认 最新

  • dsfdf854456 2016-02-26 21:23
    关注

    The first thing MkdirAll does is call os.Stat to check if the path exists and is a directory.

    func MkdirAll(path string, perm FileMode) error {
        // Fast path: if we can tell whether path is a directory or file, stop with success or error.
        dir, err := Stat(path)
        if err == nil {
            if dir.IsDir() {
                return nil
            }
            return &PathError{"mkdir", path, syscall.ENOTDIR}
        }
        ...
    

    From the docs:

    If path is already a directory, MkdirAll does nothing and returns nil.

    So no, you don't need to call os.Stat.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度