github.com/code-reading/golang@v0.0.0-20220303082512-ba5bc0e589a3/coding/bufio/05-scan.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"os"
     7  )
     8  
     9  func main() {
    10  	file, err := os.Create("scanner.txt")
    11  	if err != nil {
    12  		panic(err)
    13  	}
    14  	defer file.Close()
    15  	file.WriteString("http://studygolang.com.\nIt is the home of gophers.\nIf you are studying golang, welcome you!")
    16  	// 将文件 offset 设置到文件开头
    17  	file.Seek(0, os.SEEK_SET)
    18  	scanner := bufio.NewScanner(file)
    19  	for scanner.Scan() {
    20  		fmt.Println(scanner.Text())
    21  	}
    22  }
    23  
    24  /*
    25  output:
    26  http://studygolang.com.
    27  It is the home of gophers.
    28  If you are studying golang, welcome you!
    29  */