douzi2785 2016-02-26 13: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 13: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部