Stage 1 · Code
Standard Library Toolkit
Move Through Files Without Tripping
Small files let you get away with blunt tools. Real programs need buffered reading, buffered writing, portable paths, and a way to walk directory trees without turning memory into a dumping ground.
Why Buffering Exists
Reading from a file is not like reading from a normal Go variable. Each trip to the operating system costs work. If your program asks for one tiny piece at a time, the CPU spends too much time knocking on the OS door.
A buffer is a staging tray. Instead of making a fresh system call for every byte or every short line, Go pulls in a larger chunk once, then serves your code from that in-memory tray until it empties. Fewer system calls usually means less overhead and better performance.
| Tool | Good fit | What it helps with |
|---|---|---|
bufio.Scanner | Simple line-by-line or token-by-token reading | Convenient loop-based input processing |
bufio.Reader | More control over reads | Reading strings, bytes, or chunks with custom boundaries |
bufio.Writer | Many small writes | Fewer flushes to the operating system |
If you create a bufio.Writer, flush it before you consider the work done. Closing the file does not excuse you from that responsibility in the code you write.
Reading Large Files Safely
For a tiny config file, os.ReadFile is perfectly fine. For a giant log, it is like dragging an entire filing cabinet onto your desk because you wanted one page at a time. Streaming is calmer. You inspect one piece, do your work, then move on.
Building Portable Paths
File paths are not just strings with slashes thrown in. Different operating systems use different separators and different conventions. path/filepath exists so you do not have to hand-build those rules yourself.
They sound similar because they solve related problems, but they are not interchangeable. Local files should normally go through path/filepath.
Walking Directory Trees
Sometimes the program does not know the exact file names in advance. It only knows a starting directory and a rule such as 'visit every .json file'. filepath.WalkDir gives you a structured way to do that.
Quiz
Why does buffered I/O often improve performance?
Practice
Write a function `CountNonEmptyLines(text string) int` that uses a scanner to count lines that are not empty after trimming surrounding spaces.
Summary
- Buffers improve I/O efficiency by reducing how often your code has to call into the operating system.
bufio.Scanneris great for simple token or line processing, whileReaderandWritergive you more control.- Streaming large files keeps memory use steady because you only process one piece at a time.
path/filepathprotects you from hard-coded path separator assumptions.filepath.WalkDirlets you explore a whole directory tree with one clear callback-based pattern.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.