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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装