Reading all bytes of a file

The ioutil package provides a function to read every byte in a file and return it as byte slice. This function is convenient because you do not have to define the byte slice before doing the read. The drawback is that a really large file will return a large slice that may be bigger than expected.

The io.ReadAll() function expects a file that has already been opened with os.Open() or Create():

package main import ( "fmt" "io/ioutil" "log" "os" ) func main() { // Open file for reading file, err := os.Open("test.txt") if err != nil { log.Fatal(err) } // os.File.Read(), io.ReadFull(), and // io.ReadAtLeast() all work with a fixed // byte slice that you make before you read // ioutil.ReadAll() will read every byte // ...

Get Security with Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.