File Handling Programs
Start with File Handling Programs
Learn file handling programs through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of file handling programs.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
File exercises introduce reading, writing, error checking and cleanup. Prefer temporary directories for runnable demonstrations so programs do not overwrite real user files.
This example creates a temporary text file, reads it back and removes the directory at the end.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "go-file-example-")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "note.txt")
if err := os.WriteFile(path, []byte("Learn Go"), 0600); err != nil {
panic(err)
}
data, err := os.ReadFile(path)
if err != nil {
panic(err)
}
fmt.Println("Content:", string(data))
}
Output
Content: Learn GoTrace what the program does
The program gets an isolated temporary directory, writes Learn Go with restrictive file permissions, then reads and prints the same bytes.
Avoid common mistakes
- Check filesystem errors rather than assuming paths and permissions work.
- Do not use hard-coded shared temporary filenames that another process might overwrite.
Try it yourself
Append a second line and print the resulting file contents.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced File Handling Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.