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")
}