4

[Golang] Find Last Modified File With Specific Name Prefix

 1 year ago
source link: http://siongui.github.io/2018/04/18/go-find-last-modified-file-starts-with/
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 With Specific Name Prefix

April 18, 2018

This post shows you how to find the last modified file, name of which starts with specific prefx in Go.

We use ioutil.ReadDir to read files in the directory, but not in sub-directories. If you need to read also sub-directories, Use filepath.Walk.

package main

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

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

      for _, file := range files {
              if !file.Mode().IsRegular() {
                      continue
              }
              if strings.HasPrefix(file.Name(), prefix) {
                      if lastFile == nil {
                              lastFile = file
                      } else {
                              if lastFile.ModTime().Before(file.ModTime()) {
                                      lastFile = file
                              }
                      }
              }
      }

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

func main() {
      file, err := findLastFileStartsWith(".", "myprefix")
      if err != nil {
              panic(err)
      }
      println(file.Name())
}

Tested on: Ubuntu Linux 17.10, Go 1.10.1

References

[1][Golang] Find Last Modified File Before Specific Time

[2][Golang] Find Oldest Modified File in Directory


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK