NASutils Knowledge BaseUnofficialPolski

Go · lesson 19 of 30 · Files and errors · bonusWrite and read a file

os.WriteFile writes the whole file, O_APPEND adds to its end, a Scanner reads line by line. defer closes the file at the end.

Programming on the NAS › Go in 30 lessons

19-files.go Download 19-files.go

package main

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

func main() {
	// a whole file at once
	err := os.WriteFile("shopping.txt", []byte("two disks\na network cable\n"), 0o644)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// add to the end
	f, err := os.OpenFile("shopping.txt", os.O_APPEND|os.O_WRONLY, 0o644)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	_, err = fmt.Fprintln(f, "a UPS")
	if closeErr := f.Close(); err == nil {
		err = closeErr
	}
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// read line by line
	f, err = os.Open("shopping.txt")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer f.Close()
	lines := bufio.NewScanner(f)
	for n := 1; lines.Scan(); n++ {
		fmt.Printf("%d. %s\n", n, lines.Text())
	}
	if err := lines.Err(); err != nil {
		fmt.Println(err)
	}
}

Terminal

$ ./19-files
1. two disks
2. a network cable
3. a UPS
$ cat shopping.txt
two disks
a network cable
a UPS

Exercise

Write ten numbers into a file and read back their sum.

TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.