英文:
How to read specific line of file?
问题
我需要读取文件的特定行。我已经阅读了一些相关的主题:https://stackoverflow.com/questions/24562942/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
}
英文:
I need to read specific line of file. Some of related topics I've read: https://stackoverflow.com/questions/24562942/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
}
答案1
得分: 7
两个人说我的代码是实际的解决方案。所以我在这里发布了它。感谢@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 {
// 如果你需要返回[]bytes类型的输出,可以返回sc.Bytes()
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论