Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Read a file into a variable in Go (Golang)

Posted on July 11, 2023July 11, 2023 by admin

Table of Contents

  • Overview
  • Using ReadFile function provided by the ioutil package
  • Using os.Open and then using bytes.Buffer
  • Using os.Open and then using strings.Builder

Overview

There are various ways of reading a file into a variable in golang. Here are some of the ways

  • Using ReadFile function provided by the ioutil package
  • Using os.Open and then using bytes.Buffer
  • Using os.Open and then using strings.Builder

.Also, note reading the entire file into a variable only makes sense if you are reading a small file. If the file is large then it makes sense to read it line by line. Refer to this article for the same.

/read-large-file-line-by-line-go/

Note: Before trying out examples in this tutorial, please create a file named test.png at the location from which you will be running the program

Using ReadFile function provided by the ioutil package

https://golang.org/pkg/io/ioutil/#ReadFile

Below is the program for the same

package main
import (
"fmt"
"io/ioutil"
)
func main() {
fileBytes, err := ioutil.ReadFile("test.png")
if err != nil {
panic(err)
}
fileString := string(fileBytes)
fmt.Println(fileString)
}

Output

Some Garbage Output depending upon the file

Using os.Open and then using bytes.Buffer

https://golang.org/pkg/bytes/#Buffer

Below is the program for the same

package main
import (
"bytes"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.png")
if err != nil {
log.Fatalf("Error while opening file. Err: %s", err)
}
defer file.Close()
fileBuffer := new(bytes.Buffer)
fileBuffer.ReadFrom(file)
fileString := fileBuffer.String()
fmt.Print(fileString)
}

Output

Some Garbage Output depending upon the file

Using os.Open and then using strings.Builder

https://golang.org/pkg/strings/#Builder

Below is the program for the same

package main
import (
"bytes"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.png")
if err != nil {
log.Fatalf("Error while opening file. Err: %s", err)
}
defer file.Close()
fileBuffer := new(bytes.Buffer)
fileBuffer.ReadFrom(file)
fileString := fileBuffer.String()
fmt.Print(fileString)
}

Output

Some Garbage Output depending upon the file

Also, check out our Golang advance tutorial Series – Golang Advance Tutorial

  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP