Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "bufio"
- "flag"
- "os"
- "time"
- )
- var (
- file = flag.String("file", "", "File Path")
- )
- func init() {
- flag.Parse()
- }
- // tail prints the last n lines of the file, and
- // then polls waiting for more data to be written
- // and printing it.
- func Tail(f *os.File, n int) {
- lines := make([]string, n) // circular buffer
- i := 0
- n = 0
- r := bufio.NewReader(f)
- w := bufio.NewWriter(os.Stdout)
- for {
- line, err := r.ReadString('\n')
- if len(line) > 0 {
- lines[i] = line
- i = (i + 1) % len(lines)
- if n < len(lines) {
- n++
- }
- }
- if err != nil {
- break
- }
- }
- for j := (i - n + len(lines)) % len(lines); n > 0; j, n =
- (j+1)%len(lines), n-1 {
- w.WriteString(lines[j])
- }
- w.Flush()
- buf := make([]byte, 8192)
- for {
- time.Sleep(1e9)
- for {
- n, err := f.Read(buf)
- if n > 0 {
- w.Write(buf[0:n])
- }
- if err != nil {
- break
- }
- }
- w.Flush()
- f.Seek(0, 2) // in case the file has been truncated.
- }
- }
- func main() {
- f, err := os.Open(*file)
- defer f.Close()
- if err != nil {
- flag.Usage()
- os.Exit(1)
- }
- Tail(f, 10)
- }
Add Comment
Please, Sign In to add comment