[Golang] Find Last Modified File Before Specific Time
source link: https://siongui.github.io/2018/04/06/go-get-last-modified-file-before-specific-time/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[Golang] Find Last Modified File Before Specific Time
April 06, 2018This 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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK