How to Read an Entire File in Golang

To read an entire file in Golang, you can use the “ReadFile()” function from the “ioutil/os” package. This function reads the entire file content into a byte slice, and then you can use the “string()” function to read the file content as a string.

package main

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

func main() {
  data, err := ioutil.ReadFile("data.txt")
  if err != nil {
    log.Fatal(err)
  }

  // Print the contents of the file
  fmt.Println(string(data))
}

Output

This is a text file
The file is read line by line
Hello World

The ioutil.ReadFile() function reads an entire file into memory as a byte slice.

In this example, we used the ioutil.ReadFile() function to read the contents of the file “data.txt” into the data variable.

If there’s an error while reading the file, you can handle it using the log.Fatal() function to print the error message and exit the program.

Finally, we used the fmt.Println() function to print the file’s contents as a string.

Note: The ioutil.ReadFile() function is unsuitable for reading large files since it simultaneously loads the entire file into memory. If you need to read a large file, you should use a buffered reader to read the file in chunks.