Golang : Determine if directory is empty with os.File.Readdir() function
Problem :
You are traversing a directory tree with filepath.Walk()
function and you need to find out if a directory is empty or not.
Solution :
Instead of grabbing the entire directory content only to find out that it is empty, check if the directory is empty by reading in 1 file. Yup, just 1 file with the os.Readdir()
function and if the error returned is EOF(end of file), that means .... the directory is empty.
package main
import (
"fmt"
"io"
"os"
)
func IsDirEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer f.Close()
// read in ONLY one file
_, err = f.Readdir(1)
// and if the file is EOF... well, the dir is empty.
if err == io.EOF {
return true, nil
}
return false, err
}
func main() {
ok, err := IsDirEmpty("./")
if err != nil {
fmt.Println(err)
}
fmt.Println("Current directory is empty? : ", ok)
ok, err = IsDirEmpty("./emptydir")
if err != nil {
fmt.Println(err)
}
fmt.Println("EmptyDir directory is empty? : ", ok)
}
Sample output :
Current directory is empty? : false
EmptyDir directory is empty? : true
References :
http://golang.org/pkg/os/#File.Readdir
https://www.socketloop.com/tutorials/golang-read-directory-content-with-filepath-walk
See also : Golang : Delete certain files in a directory
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.6k Golang : How to pass data between controllers with JSON Web Token
+13.4k Golang : Get user input until a command or receive a word to stop
+11.6k Golang : Secure file deletion with wipe example
+9.2k Golang : How to get ECDSA curve and parameters data?
+11k Golang : Read until certain character to break for loop
+6.8k Mac OSX : Find large files by size
+26.2k Golang : Convert(cast) string to uint8 type and back to string
+18.3k Golang : Example for RSA package functions
+25.8k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+19.4k Golang : Close channel after ticker stopped example
+10.3k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+17.5k How to enable MariaDB/MySQL logs ?