Golang: Read File

By Xah Lee. Date: . Last updated: .

Read Whole File

here's how to read a whole file.

xBytes, xErr := os.ReadFile(filepath)

package main

import "fmt"
import "os"

func main() {

	// read whole file
	xBytes, xErr := os.ReadFile("c:/Users/xah/test.txt")

	if xErr != nil {
		panic(xErr)
		// panic means abort
	}

	// print it. String converts it to string
	fmt.Print(string(xBytes))

}

Read Whole File in golang before version 1.16 (released 2021-02-16)

For golang before version 1.16, use

xByte, xErr := ioutil.ReadFile(filepath)

io/ioutil is deprecated in go1.16. But it is still supported for backward compatibility.

Golang: Read File