Idiomatic way to read from a file. bufio.Scanner vs. bufio.Reader, etc.

1,219 views
Skip to first unread message

Brendan Tracey

unread,
Oct 14, 2013, 4:57:40 PM10/14/13
to golan...@googlegroups.com
I'm sorry if this has been discussed a lot, but I didn't see any recent threads on the topic from a search of golang-nuts. 

I'm a bit confused when I should be using bufio.Scanner vs. bufio.Reader, and when I should be using ReadLine vs ReadBytes, etc. The direct question is when are the right times for the data types?

In my specific case, I need to search a file for a specific string at the start of a line, aka "\nStart". After start will be an integer n ("\nStart=40), and the next n lines contain a set of space-delimited integers which need to be read and dealt with depending on their values. It seems like using bufio.Scanner is idiomatic to find "\nStart", but then after that bufio.Reader.ReadBytes would be the best to read in the integer lines. Is that correct? Thanks.

Brendan Tracey

unread,
Oct 14, 2013, 5:00:46 PM10/14/13
to golan...@googlegroups.com
In case my description was confusing, the file may look something like:

RandomText
% Some other text
Start=5
5 327 65 66 7
6 451 259 325 8 15 12
5 441 40 41 9
5 358 147 148 10
5 287 12 13 11

Rob Pike

unread,
Oct 14, 2013, 5:22:36 PM10/14/13
to Brendan Tracey, golan...@googlegroups.com
Scanner seems fine to do the whole thing. Just call strings.Fields for the lines after Start.

-rob

Brendan Tracey

unread,
Oct 15, 2013, 2:04:35 AM10/15/13
to golan...@googlegroups.com, Brendan Tracey
Thanks
Reply all
Reply to author
Forward
0 new messages