Stage 1 · Code
Your First Real Program
Working with Files
Read, write, and manage files safely — the foundation of any tool that persists data to disk.
Reading Files
For small files, os.ReadFile loads the entire content into memory in one call. For large files, open with os.Open and use a bufio.Scanner or io.Copy to stream the data.
Writing Files
os.WriteFile writes a byte slice to a file, creating it if it does not exist and truncating it if it does. Use os.OpenFile with flags when you need to append or control permissions explicitly.
File Paths and Directories
filepath.Join builds paths correctly for the current platform. os.MkdirAll creates nested directories. os.UserHomeDir and os.UserCacheDir give portable locations for config and data files.
Atomic Writes
Writing to a file directly risks corruption if the program is interrupted mid-write. The safe pattern is: write to a temporary file, then rename it over the target. Rename is atomic on all modern filesystems.
Power failures, OS crashes, and signal interrupts can terminate a program mid-write. A partially written JSON file is often unrecoverable. Atomic writes make your tool resilient to these events at essentially zero extra cost.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.