doudou1438 2013-07-25 16:36
浏览 781
已采纳

如何每隔10秒从Go中读取大文件的最后几行

how can I read the last two lines from a big log file without load it into memory completely?

I need read it every 10 secs(On a Win machine)...and I'm stuck trying to read the last lines..

package main

import (
    "fmt"
    "time"
    "os"
)

const MYFILE = "logfile.log"

func main() {
    c := time.Tick(10 * time.Second)
    for now := range c {
        readFile(MYFILE)
    }
}

func readFile(fname string){
    file, err:=os.Open(fname)
    if err!=nil{
        panic(err)
    }
    buf:=make([]byte, 32)
    c, err:=file.ReadAt(32, ????)
    fmt.Printf("%s
", c)


}

The log file is something like:

07/25/2013 11:55:42.400, 0.559
07/25/2013 11:55:52.200, 0.477
07/25/2013 11:56:02.000, 0.463
07/25/2013 11:56:11.800, 0.454
07/25/2013 11:56:21.600, 0.424
07/25/2013 11:56:31.400, 0.382
07/25/2013 11:56:41.200, 0.353
07/25/2013 11:56:51.000, 0.384
07/25/2013 11:57:00.800, 0.393
07/25/2013 11:57:10.600, 0.456

Thanks!

  • 写回答

4条回答 默认 最新

  • duanlu2935 2013-07-25 16:52
    关注

    You can use file.Seek() or file.ReadAt() to almost the end and then Reading forward. You can only estimate where to start seeking unless you can know that 2 lines = x bytes.

    You can get the File length by using the os.Stat(name)

    Here is an example based on ReadAt, Stat, and your sample log file:

    package main
    
    import (
        "fmt"
        "os"
        "time"
    )
    
    const MYFILE = "logfile.log"
    
    func main() {
        c := time.Tick(10 * time.Second)
        for _ = range c {
            readFile(MYFILE)
        }
    }
    
    func readFile(fname string) {
        file, err := os.Open(fname)
        if err != nil {
            panic(err)
        }
        defer file.Close()
    
        buf := make([]byte, 62)
        stat, err := os.Stat(fname)
        start := stat.Size() - 62
        _, err = file.ReadAt(buf, start)
        if err == nil {
            fmt.Printf("%s
    ", buf)
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题