typestar

Files in Go

Read a whole file, write one, or open it and defer the close.

func writeThenRead(dir string) (string, error) {
    path := filepath.Join(dir, "runs.txt")
    if err := os.WriteFile(path, []byte("go 104\n"), 0o600); err != nil {
        return "", fmt.Errorf("write: %w", err)
    }

    file, err := os.Open(path)
    if err != nil {
        return "", fmt.Errorf("open: %w", err)
    }
    defer file.Close()

    info, err := file.Stat()
    if err != nil {
        return "", fmt.Errorf("stat: %w", err)
    }

    data, err := io.ReadAll(file)
    if err != nil {
        return "", fmt.Errorf("read: %w", err)
    }
    text := strings.TrimSpace(string(data))
    return fmt.Sprintf("%d bytes: %s", info.Size(), text), nil
}

How it works

  1. os.ReadFile and os.WriteFile cover the simple cases.
  2. defer file.Close() goes right after the error check.
  3. The mode argument matters on the write path.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
575
Tokens
173
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 2 of 3 in Files & IO, step 7 of 26 in Standard library & project layout.

← Previous Next →