Beginners question: how to read a file one line at a time

413 views
Skip to first unread message

Peter Kleiweg

unread,
Jul 2, 2011, 5:07:45 AM7/2/11
to golan...@googlegroups.com

I'm still new at Go, trying to figure out how to do the simpel
things. Like, how to read a file one line at a time. I came to
the solution below, but I wonder if this is the correct way, or
if there is a simpler way to do it.

This is what I would do in C:

#define BUFSIZE 8000
char buffer[BUFSIZE + 1];
FILE *fp;

fp = fopen(filename, "r");
if (! fp) {
fprintf(stderr, "Opening file \"%s\": %s\n", filename, strerror (errno));
exit(1);
}
while(fgets(buffer, BUFSIZE, fp)) {

/* do something with buffer */


}
fclose(fp);

This is how I solved it for Go:


fd, err := os.Open(filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
f := bufio.NewReader(fd)
for {
line, isP, err := f.ReadLine()
if err == os.EOF {
break
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if isP {
fmt.Fprintln(os.Stderr, "Line too long")
os.Exit(1)
}

// do something with line

}
fd.Close()


Any comments?

--
Peter Kleiweg
http://pkleiweg.home.xs4all.nl/

John Beisley

unread,
Jul 2, 2011, 5:25:16 AM7/2/11
to Peter Kleiweg, golan...@googlegroups.com

It looks broadly correct, but the error handling is a little
repetitive. I'd be more inclined to put the meat of the work into a
function, which returns any error other than os.EOF. The caller can
then be resposible for printing the error and exiting (if there is an
error). That would likely cut down the repetitiveness.

Also, put:

defer fd.Close()

just after the error handling for opening the file - and remove
fd.Close from the end. This makes sure
that the file will be closed correctly when the function returns (or
even if it panics). It's generally idiomatic to pair the Open (or
locking operation) with the corresponding Close (or unlock etc.) of an
operation by using defer in this way.

Reply all
Reply to author
Forward
0 new messages