How to read file in Go

Here is the basic way to read a file in go using the ioutil go module. The ReadFile function requires only the file name. Then as output will give the content as a []byte and the error that will be nil if the file has successfully been read.

Code

content, err := ioutil.ReadFile(FILE NAME)

Example: read a file with ioutil

read_file.go
package main
package main

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

func main() {
	if content, err := ioutil.ReadFile("text_file.txt"); err == nil{
		fmt.Println(string(content))
	}else{
		log.Fatal(err)
	}
}

Other articles