目录

【Golang】练习 tailf 简单模拟

目录
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
)

//命令行参数解析
func FlagMsg() string {
	//定义命令行参数方式1
	var (
		follow string
	)
	flag.StringVar(&follow, "f", "", "filepath")

	//解析命令行参数
	flag.Parse()
	return follow
}

func main() {
	filepath := FlagMsg()
	file, err := os.Open(filepath)
	if err != nil {
		log.Fatalf("Open file fail:%v", err)
	}
	defer file.Close()
	reader := bufio.NewReader(file)
	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				// time.Sleep(1 * time.Second)
				continue
			} else {
				break
			}
		}
		fmt.Println(string(line))
	}
}

使用命令:

1
go run main.go -f filepath