[Golang] Find Last Modified File Before Specific Time
This post shows you how to find the last modified file before a specific time in Go. We use filepath.Walk to access all files in a directory and find the last modified file before a specific time.
package main
import (
"fmt"
"path/filepath"
"time"
)
func FindLastModifiedFileBefore(dir string, t time.Time) (path string, info os.FileInfo, err error) {
isFirst := true
min := 0 * time.Second
err = filepath.Walk(dir, func(p string, i os.FileInfo, e error) error {
if e != nil {
return e
}
if !i.IsDir() && i.ModTime().Before(t) {
if isFirst {
isFirst = false
path = p
info = i
min = t.Sub(i.ModTime())
}
if diff := t.Sub(i.ModTime()); diff < min {
path = p
min = diff
info = i
}
}
return nil
})
return
}
func main() {
dir := "/path/to/your/dir"
path, info, err := FindLastModifiedFileBefore(dir, time.Now())
if err != nil {
panic(err)
}
fmt.Println(path)
fmt.Println(info)
}
The following example is the same as finding last modified file.
Tested on: Ubuntu Linux 17.10, Go 1.10.1
References
[1] |