I need to read specific line of file. Some of related topics I've read: golang: How do I determine the number of lines in a file efficiently?, https://stackoverflow.com/questions/30692567/what-is-the-best-way-to-count-lines-in-file
I've write the following function and it works as expected, but I have doubt: may be there is better (efficient) way?
func ReadLine(r io.Reader, lineNum int) (line string, lastLine int, err error) {
sc := bufio.NewScanner(r)
for sc.Scan() {
lastLine++
if lastLine == lineNum {
return sc.Text(), lastLine, sc.Err()
}
}
return line, lastLine, io.EOF
}
Two people said my code in question is actual solution. So I've posted it here. Thanks to @orcaman for additional advice.
import (
"bufio"
"io"
)
func ReadLine(r io.Reader, lineNum int) (line string, lastLine int, err error) {
sc := bufio.NewScanner(r)
for sc.Scan() {
lastLine++
if lastLine == lineNum {
// you can return sc.Bytes() if you need output in []bytes
return sc.Text(), lastLine, sc.Err()
}
}
return line, lastLine, io.EOF
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With