Hands-On System Programming with Go
上QQ阅读APP看书,第一时间看更新

Reading from files

Getting the contents of a file can be done with an auxiliary function in the io/ioutil package, as well as with the  ReadFile function, which opens, reads, and closes the file at once. This uses a small buffer (512 bytes) and loads the whole content in memory. This is not a good idea if the file size is very large, unknown, or if the content of the file can be processed one part at a time. 

Reading a huge file from disk at once means copying all the file's content into the primary memory, which is a limited resource. This can cause memory shortages, as well as runtime errors. Reading chunks of a file at a time can help read the content of big files without causing huge memory usage. This is because the same part of the memory will be reused when reading the next chunk.

An example of reading all the content at once is shown in the following code:

package main

import (
"fmt"
"io/ioutil"
"os"
)

func main() {
if len(os.Args) != 2 {
fmt.Println("Please specify a path.")
return
}
b, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println(string(b))
}