列出目录中按创建时间排序的文件

问题描述:

I know how to list the files in a directory using ioutil.ReadDir()... but how do I sort them by creation time (from oldest to newest)? I'm using go 8.3.

我知道如何使用 ioutil.ReadDir() code>在目录中列出文件。 ..但是如何按创建时间(从最旧到最新)对它们进行排序? 我正在使用 go 8.3 code>。 p> div>

On Linux you cannot, and Go has nothing to do with it (creation time is simply not stored in most Linux file systems). On Windows you can, but not with the go standard library. Well, it may be possible with the value returned by (os.FileInfo).Sys(), but you would be better served to look for a library.

Sorting by the last modified time is fairly easy:

files, err := ioutil.ReadDir(path)
// TODO: handle the error!
sort.Slice(files, func(i,j int) bool{
    return files[i].ModTime().Before(files[j].ModTime())
})

files, err := ioutil.ReadDir(path)
//TODO
sort.Slice(files, func(i,j int) bool{
    return files[i].ModTime().Unix() < files[j].ModTime().Unix()
})