读取文本文件中的最后一行。

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

Read the final line in a text file

问题

我目前正在学习Go语言,并且我需要读取文本文件的最后一行。

我已经到处搜索了,但似乎没有一个明确的解释说明如何实现这个功能。

我该如何做到这一点?

英文:

I am currently learning Go, and I need to read the final line in a text file.

I have searched everywhere and there does not seem to be a definitive explanation on how one would do this.

How would I do this?

答案1

得分: 3

从文件的开头开始搜索可能是一个昂贵的选项,特别是如果你的文件很大。

一个更好的选择可能是使用os.Open打开文件,并使用stat方法(https://golang.org/pkg/os/#File.Stat)获取文件的大小。使用ReadAt(https://golang.org/pkg/os/#File.ReadAt)从文件的末尾开始读取(首先读取最后一个字节,然后是倒数第二个字节...),一直反向读取,直到找到第二个换行符。那就是最后一行的开头。希望这对你有帮助。

英文:

Starting the search from the very beginning of the file can be an expensive option esp. if your file(s) are large.

A better option may be to - Use os.Open to open the file and stat method (https://golang.org/pkg/os/#File.Stat) to get the size of the file. Start reading from end of the file using ReadAt (https://golang.org/pkg/os/#File.ReadAt - read the last byte first, second last byte next..), all the way reverse till you find the second newline character. That's the beginning of the last line. Hope this helps.

huangapple
  • 本文由 发表于 2017年4月2日 03:18:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/43160991.html
匿名

发表评论

匿名网友

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

确定