[Golang] Find Oldest Modified File in Directory


Find oldest modified file in the directory, excluding sub-directories, in Go. We use ioutil.ReadDir to read information of files and find the oldest modified time of file. ioutil.ReadDir does not read sub-directories. If you need to read also sub-directories, use filepath.Walk instead.

import (
      "io/ioutil"
      "os"
      "time"
)

func FindOldestFile(dir string) (oldestFile os.FileInfo, err error) {
      files, err := ioutil.ReadDir(dir)
      if err != nil {
              return
      }

      oldestTime := time.Now()
      for _, file := range files {
              if file.Mode().IsRegular() && file.ModTime().Before(oldestTime) {
                      oldestFile = file
                      oldestTime = file.ModTime()
              }
      }

      if oldestFile == nil {
              err = os.ErrNotExist
      }
      return
}

Tested on: Ubuntu Linux 17.10, Go 1.10.1

References

[1]