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/
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.