使用os.Stat和os.MkdirAll进行比较

huangapple go评论66阅读模式
英文:

Checking with os.Stat vs just os.MkdirAll

问题

我需要写入一个可能存在也可能不存在的嵌套目录中的文件。

首先,我通过os.Stat检查文件夹是否存在,如果不存在,则使用os.MkdirAll创建该文件夹,然后打开并写入文件。

我尝试删除os.Stat,只使用os.MkdirAll,看起来它可以正常工作 - 这意味着os.MkdirAll是幂等的。

我的问题是,进行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

得分: 4

MkdirAll函数的第一步是调用os.Stat函数来检查路径是否存在且为目录。

func MkdirAll(path string, perm FileMode) error {
    // 快速路径:如果我们可以确定路径是目录还是文件,则返回成功或错误。
    dir, err := Stat(path)
    if err == nil {
        if dir.IsDir() {
            return nil
        }
        return &PathError{"mkdir", path, syscall.ENOTDIR}
    }
    ...

根据文档:

如果路径已经是一个目录,MkdirAll函数不会执行任何操作并返回nil

所以,不需要调用os.Stat函数。

英文:

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.

huangapple
  • 本文由 发表于 2016年2月27日 05:21:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/35661967.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定