How to read specific line of file?

huangapple go评论76阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2015年6月7日 20:16:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/30693421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定