我需要阅读文件的特定行。我读过的一些相关主题:golang:如何有效地确定文件中的行数?, /sf/ask/2148479721/
我已经编写了以下函数并且它按预期工作,但我有疑问:可能有更好(有效)的方法吗?
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
}
Run Code Online (Sandbox Code Playgroud)
有两个人说我的问题代码是实际的解决方案。所以我把它发布在这里。感谢@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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5280 次 |
| 最近记录: |