How to check if directory on path is empty?
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
}