Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read specific line of file?

Tags:

go

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
}
like image 672
Timur Fayzrakhmanov Avatar asked Jun 07 '15 12:06

Timur Fayzrakhmanov


1 Answers

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
}
like image 191
Timur Fayzrakhmanov Avatar answered Sep 29 '22 05:09

Timur Fayzrakhmanov