Alfonso
Alfonso

Reputation: 33

Go: How to loop through files and compare ModTime to a date?

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

Upvotes: 1

Views: 5057

Answers (1)

sberry
sberry

Reputation: 132018

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\n", info.Name(), diff)
        }
    }
}

Upvotes: 11

Related Questions