如何遍历目录,根据文件时间排序

xpt*_*xpt 3 directory iteration directory-structure go

Go 提供了一个开箱即用的目录迭代功能,filepath.Walkpath/filepath包中。

但是,filepath.Walk 按词法顺序遍历文件树。如何按照最后修改日期的顺序遍历文件树?谢谢

PS(接受答案后)我认为Gofilepath.Walk函数应该为人们提供一种自己提供排序的方式,如下面的答案,其中接受type ByModTime就是人们自己对文件进行排序所需要的。

ber*_*rkk 7

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())
    }
}
Run Code Online (Sandbox Code Playgroud)