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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With