Guest User

Untitled

a guest
Dec 14th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "bufio"
  5. "flag"
  6. "os"
  7. "time"
  8. )
  9.  
  10. var (
  11. file = flag.String("file", "", "File Path")
  12. )
  13.  
  14. func init() {
  15. flag.Parse()
  16. }
  17.  
  18. // tail prints the last n lines of the file, and
  19. // then polls waiting for more data to be written
  20. // and printing it.
  21. func Tail(f *os.File, n int) {
  22. lines := make([]string, n) // circular buffer
  23. i := 0
  24. n = 0
  25. r := bufio.NewReader(f)
  26. w := bufio.NewWriter(os.Stdout)
  27. for {
  28. line, err := r.ReadString('\n')
  29. if len(line) > 0 {
  30. lines[i] = line
  31. i = (i + 1) % len(lines)
  32. if n < len(lines) {
  33. n++
  34. }
  35. }
  36. if err != nil {
  37. break
  38. }
  39. }
  40. for j := (i - n + len(lines)) % len(lines); n > 0; j, n =
  41. (j+1)%len(lines), n-1 {
  42. w.WriteString(lines[j])
  43. }
  44. w.Flush()
  45. buf := make([]byte, 8192)
  46. for {
  47. time.Sleep(1e9)
  48. for {
  49. n, err := f.Read(buf)
  50. if n > 0 {
  51. w.Write(buf[0:n])
  52. }
  53. if err != nil {
  54. break
  55. }
  56. }
  57. w.Flush()
  58. f.Seek(0, 2) // in case the file has been truncated.
  59. }
  60. }
  61.  
  62. func main() {
  63. f, err := os.Open(*file)
  64. defer f.Close()
  65. if err != nil {
  66. flag.Usage()
  67. os.Exit(1)
  68. }
  69. Tail(f, 10)
  70. }
Add Comment
Please, Sign In to add comment