I was trying to read a file line by line with the following function using bufio.NewScanner
.
func TailFromStart(fd *os.File, wg *sync.WaitGroup) {
fd.Seek(0,0)
scanner := bufio.NewScanner(fd)
for scanner.Scan() {
line := scanner.Text()
offset, _ := fd.Seek(0, 1)
fmt.Println(offset)
fmt.Println(line)
offsetreset, _ := fd.Seek(offset, 0)
fmt.Println(offsetreset)
}
offset, err := fd.Seek(0, 1)
CheckError(err)
fmt.Println(offset)
wg.Done()
}
I was expecting it to print offset in increasing order, however, it is printing the same value in each iteration until the file reaches EOF
.
127.0.0.1 - - [11/Aug/2016:22:10:39 +0530] "GET /ttt HTTP/1.1" 404 437 "-" "curl/7.38.0"
613
613
127.0.0.1 - - [11/Aug/2016:22:10:42 +0530] "GET /qqq HTTP/1.1" 404 437 "-" "curl/7.38.0"
613
613 is the total number of characters in the file.
cat /var/log/apache2/access.log | wc
7 84 613
Am I understanding it wrong, or does bufio.NewScanner
reads the entire file in memory, and iterates over that in-memory? If so, is there a better way to read line-by-line?