How to Check if Directory on Path is Empty in Go

Created
Modified

Using Readdirnames Function

The file.Readdirnames(n int) function reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order.

If n > 0, Readdirnames returns at most n names. In this case, if Readdirnames returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

The following example should cover whatever you are trying to do:

package main

import (
  "fmt"
  "io"
  "os"
)

func IsEmpty(path string) (bool, error) {

  f, err := os.Open(path)
  if err != nil {
    return false, err
  }
  defer f.Close()

  // OR f.Readdir(1)
  _, err = f.Readdirnames(1)
  if err == io.EOF {
    return true, nil
  }

  return false, err
}

func main() {
  fmt.Println(IsEmpty("a"))
  fmt.Println(IsEmpty("b"))
}
true <nil>
false <nil>

Related Tags