Golang ProgramsGolang Programs

Golang read file line by line to string

The bufio package Scanner is a suited 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 below.
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)
	}
}
 

The os.Open() function is used to open a specific text file in read-only mode and this returns a pointer of type os.File. The bufio.NewScanner() function is called in which the object os.File passed as its parameter and this returns a object bufio.Scanner which is further used on the bufio.Scanner.Split() method. The bufio.ScanLines is used as an input to the method bufio.Scanner.Split() and then the scanning forwards to each new line using the bufio.Scanner.Scan() method. As each new line is forwarded, each iteration is accessed from the method bufio.Scanner.Text() which is then appended to a slice txtlines[]. The method os.File.Close() is called on the os.File object to close the file and then a loop iterates through and prints each of the slice values.

The program after execution shows the below output line-by-line as they read it from the file.

C:\golang\file>go fmt example1.go

C:\golang\file>go run example1.go
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.

C:\golang\file>