Reading an io.Reader of unknown size into bytes array in golang

Issue

I have a file (say the descriptor is named file) opened via the os.Open() method so I want to read its contents into a bytes array.

I assume the approach would be to create the later

data := make([]byte, 10000000)

and then read the contents into it

n, err := file.Read(data)

My question is whether there is a more elegant/go-idiomatic way of going about this since by not knowing in advance the file size, I just pass a number I estimate would do (10000000) upon initialisation of the bytes array.

Solution

You can use the io/ioutil package, it has a helper function that reads an entire file into a byte slice.

package main

import "io/ioutil"

func main() {
    data, err := ioutil.ReadFile("path/to/my/file")
}

In case you have a file descriptor or any io.Reader you can use the io/ioutil package as well:

package main

import (
    "io/ioutil"
    "os"
)

func main() {
    f, _ := os.Open("path/to/my/file")
    data, err := ioutil.ReadAll(f)
}

Answered By – gonutz

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.