-
Book Overview & Buying
-
Table Of Contents
Practical Systems Programming in Go
By :
Reading files is one of the most common operations in Go, and the standard library offers multiple approaches you can use, according to your needs. For simple cases where you want the entire content at once, os.ReadFile() is the most convenient choice, returning the file contents as a byte slice. For streaming access, os.Open() combined with a bufio.Scanner instance lets you iterate line by line or even word by word, making it memory-efficient for large files. If you need lower-level control, bufio.NewReader() provides methods such as ReadBytes(), ReadString(), or ReadRune() for fine-grained reading. The next program (ch05/readFile.go) demonstrates the simplest way to read the contents of a file in Go:
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage:", os.Args[0], "<filename>")
os.Exit(1)
}
filename := os.Args[1]
data, err := os.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "...