If the directory is empty or not, it is not saved at the file system level as properties such as its name, creation time or its size (in the case of files).
As the saying goes, you cannot just get this information from os.FileInfo . The easiest way is to request the children (contents) of the directory.
ioutil.ReadDir() is a pretty bad choice, since the first one reads the entire contents of the specified directory, and then sorts them by name, and then returns a slice. The fastest way, as Dave C mentioned, is to query the children of the directory using File.Readdir() or (preferably) File.Readdirnames() .
Both File.Readdir() and File.Readdirnames() accept a parameter that is used to limit the number of returned values. It is enough to request only 1 child. Since Readdirnames() only returns names, this is faster because no further calls are required to receive (and build) FileInfo structs.
Note that if the directory is empty, io.EOF returned as an error (not an empty or nil slice), so we donβt even need a slice of the returned names.
The last code might 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 }
source share