如何检查路径上的目录是否为空?

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

How to check if directory on path is empty?

问题

在Go语言中,如何检查文件夹是否为空?可以像这样进行检查:

files, err := ioutil.ReadDir(*folderName)
if err != nil {
    return nil, err
}

// 在这里检查 files 的长度

但是我觉得可能还有更加优雅的解决方案。

英文:

How to check in Go if folder is empty? I can check like:

files, err := ioutil.ReadDir(*folderName)
if err != nil {
	return nil, err
}

// here check len of files 

But it kinda looks to me that there should be more a elegant solution.

答案1

得分: 42

一个目录是否为空并不在文件系统级别存储,就像名称、创建时间或大小(对于文件)这样的属性一样。

也就是说,你不能仅通过os.FileInfo来获取这个信息。最简单的方法是查询目录的子项(内容)。

ioutil.ReadDir()是一个很糟糕的选择,因为它首先读取指定目录的所有内容,然后按名称对它们进行排序,最后返回切片。最快的方法是像Dave C提到的那样:使用File.Readdir()或(最好是)File.Readdirnames()来查询目录的子项。

File.Readdir()File.Readdirnames()都接受一个参数,用于限制返回的值的数量。只查询一个子项就足够了。由于Readdirnames()只返回名称,所以它更快,因为不需要进一步调用来获取(和构造)FileInfo结构。

请注意,如果目录为空,会返回io.EOF作为错误(而不是空的或nil的切片),所以我们甚至不需要返回的名称切片。

最终的代码可能如下所示:

func IsEmpty(name string) (bool, error) {
    f, err := os.Open(name)
    if err != nil {
        return false, err
    }
    defer f.Close()

    _, err = f.Readdirnames(1) // 或者 f.Readdir(1)
    if err == io.EOF {
        return true, nil
    }
    return false, err // 不为空或有错误,两种情况都适用
}
英文:

Whether a directory is empty or not is not stored in the file-system level as properties like its name, creation time or its size (in case of files).

That being said you can't just obtain this information from an os.FileInfo. The easiest way is to query the children (content) of the directory.

ioutil.ReadDir() is quite a bad choice as that first reads all the contents of the specified directory and then sorts them by name, and then returns the slice. The fastest way is as Dave C mentioned: query the children of the directory using File.Readdir() or (preferably) File.Readdirnames() .

Both File.Readdir() and File.Readdirnames() take a parameter which is used to limit the number of returned values. It is enough to query only 1 child. As Readdirnames() returns only names, it is faster because no further calls are required to obtain (and construct) FileInfo structs.

Note that if the directory is empty, io.EOF is returned as an error (and not an empty or nil slice) so we don't even need the returned names slice.

The final code could look like this:

func IsEmpty(name string) (bool, error) {
	f, err := os.Open(name)
	if err != nil {
		return false, err
	}
	defer f.Close()

	_, err = f.Readdirnames(1) // Or f.Readdir(1)
	if err == io.EOF {
		return true, nil
	}
	return false, err // Either not empty or error, suits both cases
}

huangapple
  • 本文由 发表于 2015年6月8日 02:58:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/30697324.html
匿名

发表评论

匿名网友

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

确定