Getting count of files in directory using Go

Found the answer in http://blog.golang.org/go-slices-usage-and-internals

package main

import "io/ioutil"
import "fmt"

func main() {
    files,_ := ioutil.ReadDir("/Users/dgolliher/Dropbox/INBOX")
    fmt.Println(len(files))
}

ReadDir returns a list of directory entries sorted by filename, so it is not just files. Here is a little function for those wanting to get a count of files only (and not dirs):

func fileCount(path string) (int, error){
    i := 0
    files, err := ioutil.ReadDir(path)
    if err != nil {
        return 0, err
    }
    for _, file := range files {
        if !file.IsDir() { 
            i++
        }
    }
    return i, nil
}

Tags:

Go