Skip to content

Instantly share code, notes, and snippets.

@border
Created August 31, 2012 02:34
Show Gist options
  • Save border/3548169 to your computer and use it in GitHub Desktop.
Save border/3548169 to your computer and use it in GitHub Desktop.
tail by go
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment