package main

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

// import os modules if filename pass as parameters

// ReadFile function open the file
func ReadFile() {

	fmt.Printf("\n\nReading a file with ioutil.ReadFile \n")
	// embedded filename into the source code but alternative it can be dynamic
	// by pass the filename as parameters/arguments during execution of program
	// using the OS modules and argv methods
	fileName := "sample.txt"
	// alternative solution here....
	// add import of os module or IDE automatically add for us
	// uncomment the line below and comment the above line.
	// fileNameViaArgv := os.Args[1]
	data, err := ioutil.ReadFile("sample.txt")
	// uncomment the line below and comment the above line using alternative solution
	// dataArgv, err := ioutil.ReadFile(fileNameViaArgv)
	if err != nil {
		log.Panicf("ioutil.ReadFile return nil when failed reading data from file: %s", err)
	}
	fmt.Printf("\nFile Name: %s", fileName)
	fmt.Printf("\nSize: %d bytes", len(data))
	fmt.Printf("\nData: %s", data)
	// uncomment this if you using OS modules as alternative solution
	/* fmt.Printf("\nFile Name: %s", fileNameViaArgv)
	fmt.Printf("\nSize: %d bytes", len(dataArgv))
	fmt.Printf("\nData: %s", dataArgv) */
}

func main() {
	ReadFile()
}

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

// ReadFile reads the file named by filename and returns the contents.
// A successful call returns err == nil, not err == EOF. Because ReadFile
// reads the whole file, it does not treat an EOF from Read as an error
// to be reported.
func ReadFile(filename string) ([]byte, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	// It's a good but not certain bet that FileInfo will tell us exactly how much to
	// read, so let's try it but be prepared for the answer to be wrong.
	var n int64 = bytes.MinRead

	if fi, err := f.Stat(); err == nil {
		// As initial capacity for readAll, use Size + a little extra in case Size
		// is zero, and to avoid another allocation after Read has filled the
		// buffer. The readAll call will read into its allocated internal buffer
		// cheaply. If the size was wrong, we'll either waste some space off the end
		// or reallocate as needed, but in the overwhelmingly common case we'll get
		// it just right.
		if size := fi.Size() + bytes.MinRead; size > n {
			n = size
		}
	}
	return readAll(f, n)
}

Categories: io/ioutil