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
.
2 Answers
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())
})
-
The OP uses EXT4 so you're wrong dzone.com/articles/ext4-crtime-creation-time Feb 3, 2018 at 13:27
-
2True, but note two things: The comment specifying the OP's file system is newer than this answer, and the Go standard library does not support this, so you would still need to hack something together. Feb 3, 2018 at 17:17
-
This code no longer compiles (go 1.11) with the error "operator < not defined on time.Time". Note that the solution by Alexandr (with .Unix()) will compile Jan 22, 2019 at 16:39
-
Thank you for letting me know, I have updated it. Remember, you can always edit answers yourself! Jan 23, 2019 at 17:43
files, err := ioutil.ReadDir(path)
//TODO
sort.Slice(files, func(i,j int) bool{
return files[i].ModTime().Unix() < files[j].ModTime().Unix()
})
-
2While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. Jul 1, 2018 at 18:55
-