golang模仿tail命令,顯示檔案末尾指定行數的檔案內容

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。項目中需要實現讀取檔案末尾指定行數的功能(類似於tail命令),就去看了一下tail命令的實現思路。然後用go語言按照思路仿寫了一下。後面可以結合 https://github.com/fsnotify/fsnotify 實現日誌的即時輸出功能。類似於 `tail -f xxx.log`效果```package mainimport ("bufio""bytes""io""log""os""strings")func main(){lines := int64(200)file, err := os.Open("C:\\Users\\Administrator\\Desktop\\test.log")if err != nil {log.Println(err)return}fileInfo, _ := file.Stat()buf := bufio.NewReader(file)offset := fileInfo.Size() % 8192data := make([]byte, 8192) // 一行的資料totalByte := make([][][]byte, 0)readLines := int64(0)for i := int64(0); i <= fileInfo.Size() / 8192; i++{readByte := make([][]byte, 0) // 讀取一頁的資料file.Seek(fileInfo.Size() - offset - 8192*i, io.SeekStart)data = make([]byte, 8192)n, err := buf.Read(data)if err == io.EOF {if strings.TrimSpace(string(bytes.Trim(data, "\x00"))) != ""{readLines++readByte = append(readByte, data)totalByte = append(totalByte, readByte)}if readLines > lines{break}continue}if err != nil {log.Println("Read file error:", err)return}strs := strings.Split(string(data[:n]), "\n")if len(strs) == 1{b := bytes.Trim([]byte(strs[0]), "\x00")if len(b) == 0{continue}}if (readLines + int64(len(strs))) > lines{strs = strs[int64(len(strs))-lines+readLines:]}for j:=0;j<len(strs);j++{readByte = append(readByte, bytes.Trim([]byte(strs[j]+"\n"),"\x00"))}readByte[len(readByte)-1] = bytes.TrimSuffix(readByte[len(readByte)-1], []byte("\n"))totalByte = append(totalByte, readByte)readLines += int64(len(strs))if readLines >= lines{break}}totalByte = ReverseByteArray(totalByte)log.Println(ByteArrayToString(totalByte))}func ReverseByteArray(s [][][]byte) [][][]byte {for from, to := 0, len(s)-1; from < to; from, to = from+1, to-1 {s[from], s[to] = s[to], s[from]}return s}func ByteArrayToString(buf [][][]byte) string {str := make([]string, 0)for _, v := range buf {for _, vv := range v {str = append(str, string(vv))}}return strings.Join(str, "")}```如果有不當的地方,歡迎指正\x00是為了去除檔案中無效的內容,如果日誌輸出內容正常,可以刪掉相關代碼519 次點擊  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.