How to Read a Whole File into a String Variable in Go

To read a whole file into a string variable in Golang, you can use the os.ReadFile() function (available from Go 1.16 onwards) in combination with the string() function. The os.Readfile() function returns a slice of bytes that you can easily convert to a string using the string() function.

Example

package main

import (
  "fmt"
  "os"
)

func main() {
  filePath := "data.txt" // The file you want to read

  // Read the contents of the file
  contentBytes, err := os.ReadFile(filePath)
  if err != nil {
    fmt.Println("Error reading the file:", err)
    return
 }

  // Convert the byte slice to a string
  content := string(contentBytes)

  fmt.Println("File content: ")
  fmt.Println(content)
}

Output

File content:
This is a text file
We will read an entire file
Hello World

The above code reads the file specified by the filePath variable and stores the contents in the content string variable. If there’s an error while reading the file, it will print an error message and return it.

Our data.txtfile has this content:

This is a text file
We will read an entire file
Hello World

Replace the data.txt file with the path to the file you want to read.

That’s it.

Leave a Comment