Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Read file line-by-line with Scanner

  • Open

  • os.Open

  • bufio

  • NewScanner

  • Scan

  • Removes the newlines

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	filename := "random.txt"
	fh, err := os.Open(filename)
	if err != nil {
		fmt.Printf("Could not open file '%v': %v", filename, err)
		os.Exit(1)
	}
	scanner := bufio.NewScanner(fh)
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Printf("Line: %v\n", line)
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading:", err)
	}
}

{% embed include file="src/examples/read-file-with-scanner/random.txt)