Go – How to Read a File in Golang

Hello everyone, welcome to the Golang tutorial series. In this post, you will learn how to read a file in golang and this example program has been tested and shared in the same post.

Go - How to Read a File in Golang
Go – How to Read a File in Golang

The operations such as reading and writing a file in golang is a pretty easiest task to do it. In this post, we will see a quick example to read a file in go using ReadFile() function from ioutil package. The ReadFile() function will take a file name as an argument(string type) and it will return two values such as data([]byte) and error.

Example – Reading a File in Golang

In the below example, we are trying to read file content from a given file name also, we have handled an error during the unexpected scenarios. Once, the ReadFile() function ran successfully you will get []byte of a file data and same can be passed to string() function to print output.

File Content

Go - How to Read a File in Golang
Go – How to Read a File in Golang
package main

import (
	"fmt"
	"io/ioutil"
)

func main() {

	data, error := ioutil.ReadFile("data.txt")
	
	if error != nil {
		fmt.Println(error)
		return
	}

	fmt.Println(string(data))
}

References

  1. https://golang.org/doc/
  2. https://golang.org/pkg/
  3. https://golang.org/pkg/fmt/
  4. https://golang.org/pkg/fmt/#Println
  5. https://golang.org/pkg/io/ioutil/#ReadFile