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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度