Go language Implementation Tail View text file last line function, similar to the Linux tail-n 100 function

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Used primarily for the latest line view of Web service logs.

Package Main

Import
"FMT"
"OS"
"Bytes"
)

Const (
Defaultbufsize = 4096
)

Func tail (filename string, n int) (lines []string,err error) {
F,e: = os. Stat (filename)
If E = = Nil {
Size: = F.size ()
var fi *os. File
Fi,err = OS. Open (filename)
If Err = = nil{
B: = make ([]byte,defaultbufsize)
SZ: = Int64 (Defaultbufsize)
nn: = n
Btail: = bytes. Newbuffer ([]byte{})
Istart: = Size
Flag: = True
For flag {
If Istart < defaultbufsize {
SZ = Istart
Istart = 0
Flag = False
}else{
Istart-= SZ
}
_,err = fi. Seek (Istart,os. Seek_set)
If Err==nil {
Mm,e: = fi. Read (b)
If E==nil && mm>0 {
J: = mm
For i:=mm-1;i>=0;i--{
If b[i]== ' \ n ' {
BLine: = bytes. Newbuffer ([]byte{})
Bline.write (B[i+1:j])
j = I
If Btail.len () >0 {
Bline.write (Btail.bytes ())
Btail.reset ()
}

if (nn==n && Bline.len () >0) | | nn<n {//skip last "\ n"
Lines = Append (lines,bline.string ())
NN--
}
If nn==0 {
Flag = False
Break
}
}
}
If flag && j>0 {
If istart==0 {
BLine: = bytes. Newbuffer ([]byte{})
Bline.write (B[:j])
If Btail.len () >0 {
Bline.write (Btail.bytes ())
Btail.reset ()
}
Lines = Append (lines,bline.string ())
Flag = False
}else{
BB: = Make ([]byte,btail.len ())
Copy (Bb,btail.bytes ())
Btail.reset ()
Btail.write (B[:j])
Btail.write (BB)
}
}
}
}
}
Func (f *file) Seek (offset int64, whence int) (ret int64, err Error)
Func (f *file) Read (b []byte) (n int, err error) {
}
Defer fi. Close ()
}
Return
}

Func Main () {

Lns,_: = Tail ("Here is the log file path", 50)//view the last line of the file

  For _,v: = Range LNS {

  Fmt. Println (v)

}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.