Golang通过日期和时间查找最近的文件

huangapple go评论92阅读模式
英文:

Golang find most recent file by date and time

问题

我不确定我是否正确地做了这个,但最终我想找到一个目录中最近修改的文件的修改日期,并返回文件名。我目前的代码如下。有人能帮我找到比这更高效的解决方案吗?我真的觉得这个方法很笨拙。我正在获取日期并删除

package main

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

func main() {
	dir := "C:\\temp\\"
	files, _ := ioutil.ReadDir(dir)
	for _, f := range files {
		fi, _ := os.Stat(dir + f.Name())
		s := strings.Split(fi.ModTime().Format("2006-01-02 15.04.05.000"), " ")

		fdate, err := strconv.Atoi(strings.Replace(s[0], "-", "", -1))
		if err != nil {
			fmt.Println(err)
		}

		ftime, err := strconv.Atoi(strings.Replace(s[1], ".", "", -1))
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(fi.Name(), fdate+ftime)
	}

}
英文:

I am not sure if I am doing this correctly, but ultimately I would like to find the most recent modified date of a file in a directory and return the file name. The code I have so far is as follows. Can someone please help me with a more efficient solution than this. I really have a feeling this is super hacky. What I am doing is getting the dates and removing the

package main

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

func main() {
	dir := "C:\\temp\\"
	files, _ := ioutil.ReadDir(dir)
	for _, f := range files {
		fi, _ := os.Stat(dir + f.Name())
		s := strings.Split(fi.ModTime().Format("2006-01-02 15.04.05.000"), " ")

		fdate, err := strconv.Atoi(strings.Replace(s[0], "-", "", -1))
		if err != nil {
			fmt.Println(err)
		}

		ftime, err := strconv.Atoi(strings.Replace(s[1], ".", "", -1))
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(fi.Name(), fdate+ftime)
	}

}

答案1

得分: 13

请注意细节和效率。检查错误。你要求文件,所以跳过目录和其他东西。允许多个具有相同修改时间戳的文件(例如,Windows文件时间的分辨率最好为100纳秒)。你已经有了ModTime(),所以不要调用os.Stat()。直接使用time.Time方法。等等。

例如,

package main

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

func main() {
	dir := `C:\temp\` // Windows目录
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	var modTime time.Time
	var names []string
	for _, fi := range files {
		if fi.Mode().IsRegular() {
			if !fi.ModTime().Before(modTime) {
				if fi.ModTime().After(modTime) {
					modTime = fi.ModTime()
					names = names[:0]
				}
				names = append(names, fi.Name())
			}
		}
	}
	if len(names) > 0 {
		fmt.Println(modTime, names)
	}
}
英文:

Pay attention to details and efficiency. Check for errors. You asked for files so skip directories and other things. Allow for multiple files with the same modified time stamp (for example, Windows file times have a resolution of, at best, 100-nanoseconds). You already have ModTime() so don't call os.Stat(). Use time.Time methods directly. And so on.

For example,

package main

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

func main() {
	dir := `C:\temp\` // Windows directory
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	var modTime time.Time
	var names []string
	for _, fi := range files {
		if fi.Mode().IsRegular() {
			if !fi.ModTime().Before(modTime) {
				if fi.ModTime().After(modTime) {
					modTime = fi.ModTime()
					names = names[:0]
				}
				names = append(names, fi.Name())
			}
		}
	}
	if len(names) > 0 {
		fmt.Println(modTime, names)
	}
}

答案2

得分: 4

你可以比较fi.ModTime().Unix()的输出,并保留最大值来找到最近修改的文件。

例如:

package main

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

func main() {
    dir := "/tmp/"
    files, _ := ioutil.ReadDir(dir)
    var newestFile string
    var newestTime int64 = 0
    for _, f := range files {
        fi, err := os.Stat(dir + f.Name())
        if err != nil {
            fmt.Println(err)
        }
        currTime := fi.ModTime().Unix()
        if currTime > newestTime {
            newestTime = currTime
            newestFile = f.Name()
        }
    }
    fmt.Println(newestFile)
}
英文:

You can just compare the outputs of fi.ModTime().Unix() and keep the largest value to find the most recently modified file.

For example:

package main

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

func main() {
    dir := "/tmp/"
    files, _ := ioutil.ReadDir(dir)
    var newestFile string
    var newestTime int64 = 0
    for _, f := range files {
        fi, err := os.Stat(dir + f.Name())
        if err != nil {
            fmt.Println(err)
        }
        currTime := fi.ModTime().Unix()
        if currTime > newestTime {
        	newestTime = currTime
        	newestFile = f.Name()
        }
    }
	fmt.Println(newestFile)
}

huangapple
  • 本文由 发表于 2017年8月9日 05:18:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/45578172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定