[go] go wait to read the data content of the last line

Time:2021-1-28

This code is based on the video tutorial of MOOC, mainly F. seek (0, os.SEEK_ End) is moved to the end, but there is a small problem. When the open file is emptied again and the content is emptied, the data can no longer be read. For example, when the echo ” > 1.log is opened for reading, the data can no longer be read. The tail package solves this problem

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()))
    }
    //Move to the end of the file
    f.Seek(0, os.SEEK_END)
    reader := bufio.NewReader(f)
    for {
        line, err := reader.ReadBytes('\n')
        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

When using tail package test, there are re open files