如何读取文件的特定行? [英] How to read specific line of file?

查看:68
本文介绍了如何读取文件的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要阅读文件的特定行.我已阅读一些相关主题:">://://stackoverflow.com/questions/30692567/what-is-the-best-way-to-count-line-in-file

I need to read specific line of file. Some of related topics I've read: 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
}

推荐答案

两个人说我的问题代码是实际解决方案.所以我已经把它贴在这里了.感谢@orcaman的其他建议.

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
}

这篇关于如何读取文件的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆