xpt
xpt

Reputation: 22994

How to Iterate through directory, ordered based on the file time

Go provides a directory iteration functionality out of the box, with filepath.Walk in the path/filepath package.

However, filepath.Walk walks the file tree in lexical order. How can I walks the file tree in the order of last-modified date? Thx

PS (after accepting the answer) I think the Go filepath.Walk function should provide a way for people to provide the sorting themselves, like the following answer, in which accepting type ByModTime is all it take for people to sort the files themselves themselves.

Upvotes: 5

Views: 3720

Answers (1)

berserkk
berserkk

Reputation: 1007

I think, you should implement it by yourself, because filepath.Walk doesn't allow you to set order.

Look at Walk method. It calls walk, which is relying on file names from readDirNames. So basically, you should make your own Walk method with another readDirNames logic.

Here's how you get files in the order of last-modified date (note, that I'm ignoring errors):

package main

import (
    "fmt"
    "os"
    "sort"
)

type ByModTime []os.FileInfo

func (fis ByModTime) Len() int {
    return len(fis)
}

func (fis ByModTime) Swap(i, j int) {
    fis[i], fis[j] = fis[j], fis[i]
}

func (fis ByModTime) Less(i, j int) bool {
    return fis[i].ModTime().Before(fis[j].ModTime())
}

func main() {
    f, _ := os.Open("/")
    fis, _ := f.Readdir(-1)
    f.Close()
    sort.Sort(ByModTime(fis))

    for _, fi := range fis {
        fmt.Println(fi.Name())
    }
}

Upvotes: 7

Related Questions