golang模仿tail命令,显示文件末尾指定行数的文件内容

import (
	"bufio"
	"bytes"
	"io"
	"log"
	"os"
	"strings"
)

func main() {
	println(Tail("/Users/liyinlong/a.log", 3))
}

func Tail(path string, num int) string {
	lines := int64(num)
	file, err := os.Open(path)
	if err != nil {
		log.Println("读取文件内容出错了 %v", err)
		return ""
	}
	fileInfo, _ := file.Stat()
	buf := bufio.NewReader(file)
	offset := fileInfo.Size() % 8192
	data := 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)
	return 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, "")
}

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值