The os package provides simple functions for reading files. os.ReadFile reads the entire file into memory. For large files, use os.Open with io.Reader.
Goreading-files.go
30 linesLn 1, Col 1Go
os.ReadFile is simple but loads the entire file into memory. Use os.Open for streaming. os.OpenFile gives you full control over flags and permissions. Always defer f.Close() after opening.
Writing Files
Gowriting-files.go
33 linesLn 1, Col 1Go
os.WriteFile writes the entire file atomically. os.Create truncates and creates. os.OpenFile with O_APPEND adds to the end. File permissions control read/write access — 0644 for config files, 0600 for secrets.
File Information
Gofile-information.go
36 linesLn 1, Col 1Go
os.Stat returns FileInfo with size, mode, modtime, and name. Mode() returns the file permission bits. IsDir() checks if it is a directory. os.IsNotExist checks for missing files. Always check errors for file operations.
Directory Operations
Godirectory-operations.go
37 linesLn 1, Col 1Go
os.MkdirAll creates parent directories. os.ReadDir returns directory entries. filepath.Walk traverses the tree. os.RemoveAll deletes recursively — use with caution. os.Remove only removes empty directories.
Temporary Files
Gotemporary-file-patterns.go
36 linesLn 1, Col 1Go
os.CreateTemp creates temp files with random names. Always clean up with defer os.Remove. os.MkdirTemp creates temp directories. The pattern of create-temp-rename ensures atomic file replacement.
Atomic File Operations
Goatomic-write-pattern.go
59 linesLn 1, Col 1Go
Atomic writes prevent partial writes. Write to a temp file, sync to disk, then rename. The rename is atomic on most filesystems. If the process crashes mid-write, only the temp file is corrupted — the original is intact.
Always clean up temp files
Use defer os.Remove to clean up temp files. If the process crashes before cleanup, the temp file remains. Periodically clean /tmp and /var/tmp with a cron job to remove orphaned temp files.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.