zoukankan      html  css  js  c++  java
  • [Go] go等待读取最后一行的数据内容

    这段代码是参照慕课网的视频教程,主要是f.Seek(0, os.SEEK_END)移动到末尾,但是里面有个小问题,当打开的文件被重新清空内容的清空下,就再也不能到读取数据了,比如在开启读取后 echo ''>1.log 这样就再也读不到了,tail包是解决了这个问题的

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "os"
        "strings"
        "time"
    )
    
    func main() {
        readChannel := make(chan string)
        go readFile(readChannel)
        for r := range readChannel {
            fmt.Println(r)
        }
    }
    func readFile(readChannel chan string) {
        f, err := os.Open("1.txt")
        if err != nil {
            panic(fmt.Sprintf("open file error:%s", err.Error()))
        }
        //移动到文件末尾
        f.Seek(0, os.SEEK_END)
        reader := bufio.NewReader(f)
        for {
            line, err := reader.ReadBytes('
    ')
            fmt.Println(err)
            if err == io.EOF {
                time.Sleep(time.Second)
                continue
            } else if err != nil {
                panic("ReadBytes error:" + err.Error())
            }
    
            lineStr := strings.TrimSpace(string(line))
            readChannel <- lineStr
        }
    }

    使用tail包测试时,有re-open文件

  • 相关阅读:
    C#Webform 控件
    C#Webform
    MVC Razor 语法
    input file 添加
    ajax
    jquery动画
    jquery选择器,事件 dom操作
    linq 复杂查询
    webform(linq增删改查)
    asp.net内置对象
  • 原文地址:https://www.cnblogs.com/taoshihan/p/11946395.html
Copyright © 2011-2022 走看看