How to check if a directory is empty on a path?

How to check go if folder is empty? I can check how:

files, err := ioutil.ReadDir(*folderName) if err != nil { return nil, err } // here check len of files 

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

+7
source share
2 answers

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 } 
+17
source
 package main import ( "os" "path/filepath" ) func main() { i := -1 _ = filepath.Walk("./folder", func(path string, info os.FileInfo, err error) error { i++ return nil }) if i == 0 { // the folder is empty } } 

PS. filepath.Walk() will always work at least once itself

0
source

All Articles