31. Files and defer

Part 6 ended with two monsters fighting in the terminal. Everything those programs knew was gone the moment they stopped. Part 7 is about the small tools that people actually use every day: programs that read a file, change or count what is in it, write the result to another file, and take their instructions from the command line. By the end of the part you will have built a to-do list tool that you run as .\todo.exe add "buy milk", with tests that check it works.

This chapter covers files: reading them, writing them, adding to them, and finding them in folders. It starts with defer, a small Go feature that makes working with files safe.

defer

defer puts off a call until the function it is in returns, however it returns. This is exercises/31/01-defer.go:

func check(n int) {
    fmt.Println("Start")
    defer fmt.Println("End")

    if n < 0 {
        fmt.Println("Negative, so return early")
        return
    }
    fmt.Println("Not negative")
}

func main() {
    check(5)
    check(-5)
}

Output:

Start
Not negative
End
Start
Negative, so return early
End

End prints last both times, even after the early return. The defer line runs when Go reaches it, but the call it holds waits until the function is over.

A function can defer several calls. They run in the opposite order to the order they were deferred, last first, like a stack of plates where you take the top one off first:

func stack() {
    defer fmt.Println("Deferred first")
    defer fmt.Println("Deferred second")
    defer fmt.Println("Deferred third")
    fmt.Println("The body is done")
}
The body is done
Deferred third
Deferred second
Deferred first

One detail can surprise you. The arguments of a deferred call are worked out at the defer line, not at the end:

func valueNow() {
    x := 1
    defer fmt.Println("Deferred x:", x)
    x = 2
    fmt.Println("x at the end:", x)
}
x at the end: 2
Deferred x: 1

Why does this matter for files? An open file must be closed when you are done with it, so that the operating system can let go of it. A function that opens a file often has several ways out: an error here, an early return there. Writing a close call before every return is easy to get wrong. With defer f.Close() right after the file is opened, every way out closes it.

Reading a whole file

os.ReadFile reads a whole file in one call. This is exercises/31/02-read-file.go, inside main:

data, err := os.ReadFile("exercises/31/poem.txt")
if err != nil {
    fmt.Println("Error:", err)
    return
}

fmt.Println("Bytes read:", len(data))
fmt.Print(string(data))

Output:

Bytes read: 199
The kettle sings before the sun,
the cat is waiting by the door.
A program starts when it is run,
and stops when there is nothing more.

Save your work before you go:
a file remembers what you know.

os.ReadFile gives back two values, like strconv.Atoi: the content and an error. The content has the type []byte, a slice of bytes. Chapter 12 showed that a string is made of bytes. A file is made of bytes too, and it does not have to be text: a photo is also a file. Go therefore hands you the raw bytes, and string(data) turns them into a string you can print and search. The poem has 199 bytes, counting the line endings.

Change the name to poem.tx and run it again. On Windows you get:

Error: open exercises/31/poem.tx: The system cannot find the file specified.

The error says what Go tried (open), which file, and what went wrong. On Linux or macOS the last part reads no such file or directory instead. Either way, the program did not crash: it checked err and stopped politely.

os.ReadFile is the simplest way to read a file, and the right one for small files. It holds the whole file in memory at once, so for a file of several gigabytes, read it line by line instead, as shown below.

Writing a whole file

os.WriteFile is the other direction. It creates the file if it does not exist, and replaces everything in it if it does. This is exercises/31/03-write-file.go, inside main:

text := "Hello from Go!\nThis file was written by a program.\n"

err := os.WriteFile("greeting.txt", []byte(text), 0644)
if err != nil {
    fmt.Println("Error:", err)
    return
}
fmt.Println("Wrote greeting.txt")

It then reads the file back and prints it:

Wrote greeting.txt
Hello from Go!
This file was written by a program.

Three things to notice:

  • []byte(text) turns a string into bytes, because that is what os.WriteFile takes. It is the opposite of string(data).
  • 0644 is the file's permissions: who may read and write it. They matter on Linux and macOS, where 0644 means "I can read and write it, everyone else can only read it". On Windows they have almost no effect. Write 0644 for ordinary files and move on.
  • The function returns only an error, since there is nothing else to give back.

Look in your go-work folder: greeting.txt is there. Open it in VS Code to see that it is an ordinary text file.

Change the text in exercises/31/03-write-file.go and run it again. Open greeting.txt: the old text is gone, replaced by the new.

Reading line by line

Most text files are a list of lines, and most programs want them one at a time. That takes three steps: open the file, wrap it in a scanner that splits it into lines, and loop. This is exercises/31/04-line-numbers.go:

func printNumbered(name string) error {
    f, err := os.Open(name)
    if err != nil {
        return err
    }
    defer f.Close()

    scanner := bufio.NewScanner(f)
    number := 0
    for scanner.Scan() {
        number++
        fmt.Printf("%2d  %s\n", number, scanner.Text())
    }
    return scanner.Err()
}

func main() {
    err := printNumbered("exercises/31/poem.txt")
    if err != nil {
        fmt.Println("Error:", err)
    }
}

Output:

 1  The kettle sings before the sun,
 2  the cat is waiting by the door.
 3  A program starts when it is run,
 4  and stops when there is nothing more.
 5
 6  Save your work before you go:
 7  a file remembers what you know.

Step by step:

  • os.Open(name) opens the file for reading. It gives back an open file, f, and an error. Opening is where a missing file is noticed.
  • defer f.Close() comes straight after the error check. Not before it: if opening failed, there is no file to close.
  • bufio.NewScanner(f) makes a scanner, from the same bufio package as the reader in Chapter 15.
  • scanner.Scan() reads the next line and returns true, or returns false when there is nothing more. That makes it a perfect for condition.
  • scanner.Text() gives the line that was just read, without its line ending. Windows line endings (\r\n) and Linux ones (\n) are both removed.
  • scanner.Err() is checked after the loop. Scan returns false both at the end of the file and when something went wrong, and Err tells the two apart: it is nil at a normal end.

One example of "something went wrong": a scanner refuses a single line longer than 64 KB, and scanner.Err() then reports bufio.Scanner: token too long. Ordinary text files never come near that, but skip the Err check and the program would quietly stop halfway and report success.

The scanner reads a little at a time, so this works on a file of any size.

Change exercises/31/04-line-numbers.go so that it skips empty lines and does not give them a number.

Writing piece by piece

To write a file in many small pieces, for example one line per loop round, use os.Create and a bufio.Writer. This is exercises/31/05-write-table.go:

func writeTable(name string, n int) error {
    f, err := os.Create(name)
    if err != nil {
        return err
    }
    defer f.Close()

    w := bufio.NewWriter(f)
    for i := 1; i <= 10; i++ {
        fmt.Fprintf(w, "%2d x %d = %3d\n", i, n, i*n)
    }

    err = w.Flush()
    if err != nil {
        return err
    }
    return f.Close()
}

main calls writeTable("table.txt", 7), and table.txt then holds:

 1 x 7 =   7
 2 x 7 =  14
 3 x 7 =  21
...
10 x 7 =  70
  • os.Create(name) opens a file for writing. Like os.WriteFile, it creates the file, or empties it if it already exists.
  • bufio.NewWriter(f) collects what you write in memory and sends it to the file in large pieces, which is much faster than many tiny writes.
  • fmt.Fprintf(w, ...) is fmt.Printf with one extra argument at the front: where to write. fmt.Fprintln and fmt.Fprint work the same way. The F is for "file".
  • w.Flush() sends whatever is still waiting in memory to the file.

Forget w.Flush() and the program runs with no error, but the file is empty, or missing its last part. The writer was still holding the text when the program ended. Always flush, and check its error.

Two error questions remain. First, the fmt.Fprintf errors are not checked in the loop. A bufio.Writer remembers the first error it meets and refuses to write after that, and Flush then returns that error. So checking Flush covers the whole loop.

Second, the file is closed twice: return f.Close() at the end, and the deferred f.Close(). When writing, closing can fail, for example on a full disk, and that error means the data may not be saved. So on the success path you close the file yourself and return the error. The deferred Close is a safety net for the early returns. When it runs after the file is already closed, it returns an error that nobody looks at, which is fine: the real result was already returned.

For reading, a plain defer f.Close() is enough. Nothing you read can be lost when closing.

Adding to the end of a file

os.Create and os.WriteFile both throw away what was in the file. To add lines to the end instead, for a log or a diary, use os.OpenFile. This is exercises/31/06-append-log.go:

func appendLine(name string, line string) error {
    f, err := os.OpenFile(name, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return err
    }
    defer f.Close()

    _, err = fmt.Fprintln(f, line)
    if err != nil {
        return err
    }
    return f.Close()
}

os.OpenFile takes the name, a set of flags that say how to open the file, and the permissions. The flags are joined with |:

Flag Meaning
os.O_APPEND Write at the end, after what is already there.
os.O_CREATE Create the file if it does not exist.
os.O_WRONLY Open for writing only.

fmt.Fprintln writes straight to the file here, with no bufio.Writer, because there is only one line. It returns two values: the number of bytes written, which is not needed, and an error.

main adds The program ran. to log.txt, then prints the file. Run it three times, and the last run prints:

The program ran.
The program ran.
The program ran.

When the file is missing

Sometimes a missing file is not a problem at all. A settings file that the user has not made yet just means "use the defaults". This is exercises/31/07-missing-file.go:

// loadName returns the name in name.txt, or "World" if there is no such file.
func loadName() (string, error) {
    data, err := os.ReadFile("name.txt")
    if errors.Is(err, os.ErrNotExist) {
        return "World", nil
    }
    if err != nil {
        return "", err
    }
    return strings.TrimSpace(string(data)), nil
}

errors.Is(err, os.ErrNotExist) asks: does this error mean "the file does not exist"? If so, the function returns the default with no error. Any other problem, such as not being allowed to read the file, is still returned as an error. Run it, and it prints Hello, World!. Make a file name.txt in go-work that holds your name, and run it again.

Why errors.Is and not a comparison with ==? The error from os.ReadFile holds more than "does not exist": it also holds the operation and the file name. Chapter 33 explains how errors can carry other errors inside them, and how errors.Is looks inside. For now, use the line as it is.

Where files are found

"greeting.txt" and "exercises/31/poem.txt" are relative paths. They do not start at the top of a drive, like C:\. Go looks for them starting from the working directory: the folder that the terminal is in when you run the program. You run every program from C:\go-work, so greeting.txt means C:\go-work\greeting.txt, and exercises/31/poem.txt means C:\go-work\exercises\31\poem.txt.

This means the same program finds different files depending on where you run it. If you cd exercises first and then run go run 31/02-read-file.go, it looks for C:\go-work\exercises\exercises\31\poem.txt, which does not exist. When a program cannot find a file that you can see, check the folder you ran it from first.

To build a path from parts, use filepath.Join from the path/filepath package. It puts the right separator between the parts: \ on Windows and / on Linux and macOS. Go accepts / on Windows too, which is why "exercises/31/poem.txt" worked above, but filepath.Join gives the form the user expects to see. This is exercises/31/08-paths.go, inside main:

dir, err := os.Getwd()
if err != nil {
    fmt.Println("Error:", err)
    return
}
fmt.Println("Working directory:", dir)

path := filepath.Join("exercises", "31", "poem.txt")
fmt.Println("Path:", path)
fmt.Println("Base:", filepath.Base(path))
fmt.Println("Dir: ", filepath.Dir(path))
fmt.Println("Ext: ", filepath.Ext(path))

data, err := os.ReadFile(path)
if err != nil {
    fmt.Println("Error:", err)
    return
}
fmt.Println("Bytes:", len(data))

Output on Windows:

Working directory: C:\go-work
Path: exercises\31\poem.txt
Base: poem.txt
Dir:  exercises\31
Ext:  .txt
Bytes: 199

os.Getwd ("get working directory") tells you where the program is running. filepath.Base gives the last part of a path, filepath.Dir everything before it, and filepath.Ext the extension, with its dot.

Listing a folder

os.ReadDir lists what is inside one folder. This is exercises/31/09-list-folder.go, inside main:

folder := filepath.Join("exercises", "31", "sample")

entries, err := os.ReadDir(folder)
if err != nil {
    fmt.Println("Error:", err)
    return
}

for _, entry := range entries {
    if entry.IsDir() {
        fmt.Println("[folder]", entry.Name())
    } else {
        fmt.Println("        ", entry.Name())
    }
}

Output:

         readme.txt
[folder] recipes
         shopping.txt

The entries come back sorted by name. Each has a Name method and an IsDir method, which says whether it is a folder. os.ReadDir does not look inside recipes. For that, you walk.

Walking a folder tree

filepath.WalkDir visits a folder, every file in it, every folder in it, every file in those, and so on, all the way down. For each one, it calls a function that you give it. This is exercises/31/10-walk.go, inside main:

root := filepath.Join("exercises", "31", "sample")
files := 0
var total int64

err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
    if err != nil {
        return err
    }
    if d.IsDir() {
        fmt.Println("[folder]", path)
        return nil
    }

    info, err := d.Info()
    if err != nil {
        return err
    }
    fmt.Printf("%8d %s\n", info.Size(), path)
    files++
    total += info.Size()
    return nil
})
if err != nil {
    fmt.Println("Error:", err)
    return
}

fmt.Printf("%d files, %d bytes\n", files, total)

Output on Windows:

[folder] exercises\31\sample
      85 exercises\31\sample\readme.txt
[folder] exercises\31\sample\recipes
      80 exercises\31\sample\recipes\rice.txt
      39 exercises\31\sample\recipes\soup.txt
      14 exercises\31\sample\shopping.txt
4 files, 218 bytes

There is something new in the middle of this code. Chapter 24 passed a named function to slices.SortFunc. Here the function is written right where it is needed, with func and no name. This is a function literal. It is a whole function, with parameters, a body and return, used as a value. A function literal can use the variables of the function around it, so it can add to files and total, which belong to main. A named function at the top level could not.

WalkDir calls your function once for every file and folder, with three arguments:

  • path: the path of this file or folder, starting with root.
  • d: an fs.DirEntry, the same kind of entry os.ReadDir gives, from the io/fs package. It has Name, IsDir and Info.
  • err: not nil if WalkDir could not read this entry, for example a folder you have no permission to open.

What your function returns tells WalkDir what to do next. nil means "carry on". An error stops the walk at once, and WalkDir returns that same error to main.

d.Info() gives more details about the file, including Size(), the size in bytes. The size has the type int64, a whole number that can hold much larger values than you would ever count by hand, because files can be huge. total is declared as an int64 so that the two can be added; Go does not mix number types, as Chapter 13 showed.

Change exercises/31/10-walk.go to walk "exercises" instead, and print only the files whose name ends in .go. strings.HasSuffix from Chapter 14 will help.

Homework

Homework starters are in exercises/31/homework/. Each one runs as it is, with a placeholder. Files the programs write are created in go-work. Delete them to start again.

Problem 1 — A shopping list file

Open exercises/31/homework/01-shopping-list.go. Write writeList, which creates a file and writes one item per line, numbered from 1, like 1. rice. Use os.Create, a bufio.Writer and fmt.Fprintf. main is finished: it writes shopping.txt, then reads it back and prints it.

Problem 2 — The longest line

Open exercises/31/homework/02-longest-line.go. Write longestLine, which reads a file line by line and returns the number and the text of its longest line. Close the file with defer, and check scanner.Err(). For the poem, the answer is line 4.

Problem 3 — A run counter

Open exercises/31/homework/03-run-counter.go. Write countLines, which counts the lines in a file, where a missing file has 0 lines and is not an error. Then write appendLine, which adds one line to the end of a file. main is finished: each run prints This is run N. and adds Run N to runs.txt.

Challenge — A folder report

Open exercises/31/homework/04-folder-report.go. Walk exercises/31/sample with filepath.WalkDir. Count the files (not the folders), add up their sizes, and find the largest file. Print the three results.

Stuck or done? Open the homework solutions page.