Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting count of files in directory using Go

Tags:

go

How might I get the count of items returned by io/ioutil.ReadDir()?

I have this code, which works, but I have to think isn't the RightWay(tm) in Go.

package main

import "io/ioutil"
import "fmt"

func main() {
    files,_ := ioutil.ReadDir("/Users/dgolliher/Dropbox/INBOX")
    var count int
    for _, f := range files {
        fmt.Println(f.Name())
        count++
    }
    fmt.Println(count)
}

Lines 8-12 seem like way too much to go through to just count the results of ReadDir, but I can't find the correct syntax to get the count without iterating over the range. Help?

like image 418
golliher Avatar asked Jun 08 '14 02:06

golliher


2 Answers

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))
}
like image 166
golliher Avatar answered Oct 21 '22 04:10

golliher


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
}
like image 28
Rod Avatar answered Oct 21 '22 03:10

Rod