Golang – Reading a text file

This is a recipe for reading a text file.

package main

import (

func errCallback(e error) {
	// General log error to console.
	if e != nil {

func openTextFile(fname string) {
	// os.Open returns file pointer and error
	fptr, e := os.Open(fname)
	defer fptr.Close()

	// bufio.NewScanner() accepts file pointer as argument and return a scanner object
	scanner := bufio.NewScanner(fptr)

	// Read the file line by line
	for scanner.Scan() {
		// Print out the text line by line.

func main() {


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