2015-06-07 70 views
1

我需要讀取特定的文件行。我讀過的一些相關主題: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 
} 
+1

你不知道該怎麼做,但你已經編寫了你想要的代碼嗎? –

+0

是的,你說得對。我的英語不太好) –

+2

你的解決方案看起來不錯。我不會改變它,除非你是希望做一些特別的東西[所以舉例來說,如果你想成爲能夠快速找到需要的線路,從客戶端請求的數據說,DB的風格,你可以考慮緩存整個文件在內存中的一個切片,然後你可以簡單地通過使用索引作爲行號抓住該行] – orcaman

回答

1

兩個人說我有問題的代碼是實際的解決方案。所以我把它貼在這裏。感謝@orcaman獲取更多建議。

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 
}