ReadFile WriteFile And Stat For Files

Handle small files with os.ReadFile, os.WriteFile, and os.Stat: one call each for write, read, and metadata, with IsNotExist classifying missing paths.

GoCli Tooling

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"os"
)

func main() {
	// WriteFile: creates the file or truncates an existing one; the 0o644 mode applies only on creation
	path := "notes.txt"
	if err := os.WriteFile(path, []byte("first line\nsecond line\n"), 0o644); err != nil {
		panic(err)
	}

	// ReadFile slurps the whole content in one call, the most direct route for small files
	data, err := os.ReadFile(path)
	if err != nil {
		panic(err)
	}
	fmt.Printf("content: %q\n", string(data))

	// Stat fetches metadata: size and whether the path is a directory
	info, err := os.Stat(path)
	if err != nil {
		panic(err)
	}
	fmt.Println("size:", info.Size(), "dir:", info.IsDir())

	// Reading a missing file returns an error: os.IsNotExist classifies absent paths
	if _, err := os.ReadFile("missing.txt"); err != nil {
		fmt.Println("missing:", os.IsNotExist(err))
	}
	os.Remove(path)
}

A closer look

The work happens entirely inside the function main — everything else is wiring.

err is tested at 4 places, and a non-nil one aborts the run with panic(err).

Watch out for

  • The dependency list is empty; the language runtime covers it all.
  • The snippet does not return errors — any non-nil err ends the run immediately.

Applying it

The entry point to reuse: func main()

Output lines are prefixed (content:, size:, missing:), leaving no doubt about which step printed what.

Statements that matter

if err != nil {
panic(err)
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
It stops. All 4 `if err != nil` branches ends in `panic(err)` — nothing continues past a failed call.
What does ReadFile WriteFile And Stat For Files print when run?
Invoke the file as-is — the `content:`, `size:`, `missing:` prefixes identify which step printed each line.