[Go]Open a file and read its contents

Open the file and read its contents, if the file does not exist exit the program with exit status 1, log.Fatal() not only logs the problem but also do os.Exit(1)

package	main

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

func main() {
	// evaluate the error, if not nil means error occur exit 
	if contents, e := openFile("log.txt"); e != nil {
		log.Fatal(e)
	} else {
		// because the contents is byte slice.
		// and the byte slice is a string slice.
		// conversion to actual string only need to use the type casting method i.e. string()
		fmt.Println(string(contents))
	}
}

func openFile(fn string) ([]byte, error) {
	// check if the file exists.
	if _, err := os.Stat(fn); os.IsNotExist(err) {
		return nil, err
	} else {
		// if the file exists read the file contents
		// return byte slice and error.
		b, e := ioutil.ReadFile(fn)
		return b, e
	}
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s