dsfjnxjlbqv9812 2017-08-08 21:18
浏览 379
已采纳

Golang按日期和时间查找最新文件

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)
    }

}
  • 写回答

2条回答 默认 最新

  • douhoushou8385 2017-08-08 22:52
    关注

    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏