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.
Code
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
errends 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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.