我需要阅读文件的特定行。我已阅读一些相关主题:golang:如何有效确定文件中的行数?,https://stackoverflow.com/questions/30692567/what-is-the-best-way-to-count-lines-in-file
我已经编写了以下函数,它可以按预期工作,但是我怀疑:可能有更好(有效)的方法吗?
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
}
两个人说我的代码是实际的解决方案。所以我已经贴在这里了。感谢@orcaman的其他建议。
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句