-1

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?

ungless
  • 378
  • 3
  • 14
  • 2
    It's the same concept in any language. Are you asking you to scan a file by lines? https://golang.org/pkg/bufio/#example_Scanner_lines – JimB Apr 01 '17 at 19:20
  • @JimB That is correct. Could you perhaps offer an explanation in Go? – ungless Apr 01 '17 at 19:25
  • 1
    What question do you have about the example given, or other answers like https://stackoverflow.com/questions/8757389/reading-file-line-by-line-in-go/16615559#16615559? – JimB Apr 01 '17 at 19:36
  • @JimB Where in that code returns the final line of the file. I'm still a bit confused about how to get that information. – ungless Apr 01 '17 at 19:41
  • I'm not sure how else to state it, the last line you read will be the final line. – JimB Apr 01 '17 at 19:46
  • @JimB But how do I catch that? – ungless Apr 01 '17 at 19:47
  • 1
    you assign it to a variable: https://play.golang.org/p/6mCIJDW2jy – JimB Apr 01 '17 at 20:35

1 Answers1

3

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.

Ravi R
  • 1,692
  • 11
  • 16