Go program to reading plain text files
The bufio package
Scanner
generally used for reading the text by lines or words from a file. The following source code snippet shows reading text line-by-line from the plain text file as below.
Example
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.txt")
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var txtlines []string
for scanner.Scan() {
txtlines = append(txtlines, scanner.Text())
}
file.Close()
for _, eachline := range txtlines {
fmt.Println(eachline)
}
}
Output
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nunc a mi dapibus, faucibus mauris eu, fermentum ligula.
Donec in mauris ut justo eleifend dapibus.
Donec eu erat sit amet velit auctor tempus id eget mauris.
The program after execution shows the below output line-by-line as they read it from the file.
Most Helpful This Week
10 Countries Paying Highest Salaries to Cybersecurity Professionals
Golang program for implementation of Pancake Sort
Golang program for implementation of Knuth–Morris–Pratt (KMP) Algorithm
Illustration of Checkpoint Synchronization in Golang
Golang program for implementation of Median of Medians
Expected <type>, but got <type> error in Golang