Reading Files
Read manageable files with os.ReadFile or scan lines from os.Open; check scanner errors and account for its token limit.
Use os.ReadFile when a file is small enough to fit in memory. For a file that contains lines of text, bufio.Scanner reads one line at a time instead of loading the whole file.
Open the file, close it when finished, and check Scanner.Err after the loop. A read error also stops scanning, so the loop ending does not always mean the whole file was read.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("input.txt")
if err != nil {
panic(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
panic(err)
}
}In production
os.ReadFile uses memory equal to the file size. Scanner reads one line at a time and has a default maximum line length of about 64 KiB. Increase that limit with Scanner.Buffer before scanning, or use bufio.Reader for longer lines. Always check the final read error.
Enjoyed this? Get more software craft delivered to your inbox.