I'm trying to read lines in files. I'd like to easily open a file, and parse through the lines one at a time, and remove some boilerplate opening and closing. I'm passing back a pointer to the 'scanner'. Is this just a dumb approach? Has the scanner already read the contents because of the Split? Are there better ways of doing this? Any insight regarding best practices are appreciated.
func main() {
var path string
if len(os.Args) > 1 {
err, scanner := fileScanner(path)
if err == nil {
// Go through file line by line.
for scanner.Scan() {
fmt.Println(scanner.Text())
// or do other stuff
}
// so how do I make sure to close the file?
}
}
}
// Return a scanner for a file.
func fileScanner(path string) *bufio.Scanner {
file, err := os.Open(path)
if err != nil {
return err
}
//defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
return err, scanner
}