Go — Scanning files and checking errors
In Go, a Scanner reads a file one token at a time. After Scan stops, check Err to distinguish the end of input from a read failure.
A simple example
Read back one letter
- Start with A
- Do this Write, then read
- Result A
package main
import "fmt"
import "os"
func main() {
file, err := os.CreateTemp("", "letter")
if err != nil { panic(err) }
defer os.Remove(file.Name())
defer file.Close()
if _, err = file.WriteString("A"); err != nil { panic(err) }
data, err := os.ReadFile(file.Name())
if err != nil { panic(err) }
fmt.Println(string(data))
}
A
Sum two lines from a temporary report
Defer schedules cleanup until the function returns. The calls run in reverse registration order, closing the file before removing it. After the scan loop, scanner.Err distinguishes a read failure from normal completion.
Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.
Run the example
Go 1.20 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func sumReport() (int, error) {
file, err := os.CreateTemp("", "readings")
if err != nil {
return 0, err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err := file.WriteString("4\n7\n"); err != nil {
return 0, err
}
if _, err := file.Seek(0, 0); err != nil {
return 0, err
}
scanner := bufio.NewScanner(file)
total := 0
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
n, err := strconv.Atoi(line)
if err != nil {
return 0, err
}
total += n
}
return total, scanner.Err()
}
func main() {
total, err := sumReport()
if err != nil {
panic(err)
}
fmt.Println(total)
}
11
The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.
Try it yourself
Add a third line containing 12.
Check your answer
The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.