Files and IO
| os.ReadFile | |
| os.WriteFile | |
| Buffered streaming | |
| Walk directories |
os.ReadFile
os.ReadFile reads a whole file into memory in one call. It returns the bytes and an error, so check the error first. For small configs and notes this single call is all you need. Larger files deserve streaming, which comes later in this lesson.
package main
import (
"fmt"
"os"
)
func main() {
data, err := os.ReadFile("notes.txt")
if err != nil {
fmt.Println(err)
return
}
fmt.Print(string(data))
}
The path is relative to the working directory of the running program. A missing file shows up as an error, not as empty data. Convert the bytes to a string only when you plan to print or parse text.
os.WriteFile
os.WriteFile writes bytes to a path in one call and creates the file when it is missing. The last argument sets permission bits, and 0644 is the usual default. One call replaces the whole file, which keeps small saves simple. For big reports switch to a buffered writer instead.
package main
import (
"fmt"
"os"
)
func main() {
text := []byte("hello, files\n")
if err := os.WriteFile("hello.txt", text, 0644); err != nil {
fmt.Println(err)
return
}
fmt.Println("written")
}
go run main.go
written
Buffered streaming
bufio adds buffering around readers and writers so small reads do not turn into many slow system calls. Scanner splits input into lines with almost no setup. Always check scan errors after the loop ends. The pattern below counts lines in files of any size.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
in, err := os.Open("big.txt")
if err != nil {
fmt.Println(err)
return
}
defer in.Close()
scanner := bufio.NewScanner(in)
count := 0
for scanner.Scan() {
count++
}
if err := scanner.Err(); err != nil {
fmt.Println(err)
return
}
fmt.Println(count)
}
defer closes the file when main returns, even on the error paths above. Scanner work happens line by line, so memory stays flat. Writers get the same treatment with bufio.NewWriter plus Flush at the end.
Walk directories
filepath.WalkDir visits every entry under a directory tree. The callback runs once per file and folder, top down. Return an error from the callback to stop the walk early. Skipping directories keeps the output focused on real files.
package main
import (
"fmt"
"io/fs"
"path/filepath"
)
func main() {
err := filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
fmt.Println(path)
}
return nil
})
if err != nil {
fmt.Println(err)
}
}
The callback receives the path, the entry, and any error met on the way down. Handle that error inside the callback or the walk cannot continue past broken links. WalkDir reads lazily, so huge trees do not flood memory.
Next: HTTP servers
Article author: Arthur Isaev