Golang – Reading a text file

This is a recipe for reading a text file.

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

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

func openTextFile(fname string) {
	// os.Open returns file pointer and error
	fptr, e := os.Open(fname)
	errCallback(e)
	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.
		fmt.Println(scanner.Text())
	}
}

func main() {
	openTextFile("test.txt")
}

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