I'm trying to loop through files in a directory and compare their ModTime against a certain date in order to delete older files.
I'm using ioutil.ReadDir() to get the files but I'm stuck with how to retrieve the ModTime of each file.
Thanks
I'm trying to loop through files in a directory and compare their ModTime against a certain date in order to delete older files.
I'm using ioutil.ReadDir() to get the files but I'm stuck with how to retrieve the ModTime of each file.
Thanks
The return from ioutil.ReadDir
is ([]os.FileInfo, error)
. You would simply iterate the []os.FileInfo
slice and inspect the ModTime()
of each. ModTime()
returns a time.Time
so you can compare in any way you see fit.
package main
import (
"fmt"
"io/ioutil"
"log"
"time"
)
var cutoff = 1 * time.Hour
func main() {
fileInfo, err := ioutil.ReadDir("/tmp")
if err != nil {
log.Fatal(err.Error())
}
now := time.Now()
for _, info := range fileInfo {
if diff := now.Sub(info.ModTime()); diff > cutoff {
fmt.Printf("Deleting %s which is %s old
", info.Name(), diff)
}
}
}