j3d
j3d

Reputation: 9724

List Files in a Directory Sorted by Creation Time

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.

Upvotes: 6

Views: 9875

Answers (2)

Milo Christiansen
Milo Christiansen

Reputation: 3294

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())
})

Upvotes: 14

Alexandr Vlasov
Alexandr Vlasov

Reputation: 49

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

Upvotes: 4

Related Questions