我需要阅读特定的文件行。我读过的一些相关主题: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
我已经编写了以下功能,它按预期工作,但我有疑问:可能有更好(有效)的方式吗?
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
}
答案 0 :(得分:1)
两个人说我的代码是实际的解决方案。所以我在这里发布了它。感谢@orcaman提供更多建议。
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
}