go - How to read a file line by line and return how many bytes have been read? -
the case :
- i want read log "tail -f" *nix
- when kill program can know how many bytes have read,and can use seek
- when program start again,will continue read log line line depend seek data in step 2
i want bytes when use bufio.newscanner line reader read line
eg:
import ... func main() { f, err := os.open("111.txt") if err != nil { log.fatal(err) } f.seek(0,os.seek_set) scan := bufio.newscanner(f) scan.scan() { log.printf(scan.text()) //what want how many bytes @ time when read line }//this program read line
}
thx! ==================================update========================================== @twotwotwo close want,but want change io.reader io.readerat, , want,i write demo use io.reader:`
import ( "os" "log" "io" ) type reader struct { reader io.reader count int } func (r *reader) read(b []byte) (int, error) { n, err := r.reader.read(b) r.count += n return n, err } func (r *reader) count() int { return r.count } func newreader(r io.reader) *reader { return &reader{reader: r} } func readline(r *reader) (ln int,line []byte,err error) { line = make([]byte,0,4096) { b := make([]byte,1) n,er := r.read(b) if er == io.eof { err = er break } if n > 0{ c := b[0] if c == '\n' { break } line = append(line, c) } if er != nil{ err = er } } ln = r.count() return ln,line,err } func main() { f, err := os.open("111.txt") if err != nil { log.fatal(err) } fi,_:=os.stat("111.txt") log.printf("the file have %v bytes",fi.size()) co := newreader(f) { count,line,er := readline(co) if er == io.eof { break } log.printf("now read line :%v",string(line)) log.printf("in have read %v bytes",count) } }`
this program can tell me how many bytes have read,but cannt read start anywhere want,so think if use io.readerat must can it. again!
you consider approach based on os.file
.
see activestate/tail, monitor state of file, , uses os.file#seek() resume tailing file within point.
see tail.go
.
Comments
Post a Comment