Golang : Reading File Line By Line

Below golang program reads a file line by line by creating a Reader object from the io.Reader object using bufio. Package bufio wraps io.Reader object creating a Reader.

  • Reader object makes use of the ReadString function to read until the first occurrence of a delimiter is found.
    • ReadString returns an error i.e err != nil if the data that is being read does not end in the delimiter.
    • ReadString also return an error ( io.EOF ) if it encounters an error before reading the delimiter.
    • In the below example we read the contents of the text file with file path /tmp/algo.txt
         $ cat /tmp/algo.txt
         Merge Sort
         QuickSort
         Depth First Search
         Breadth First Search
         N Queens Problem
         Matrix Chain Multiplication 
      

Go ( Golang ) : Reading a file line by line using reader

package main

import (
    "bufio"
    "io"
    "os"
    "fmt"
)

func check(e error) {
    if e != nil {
        panic(e)
    }   
}

func ReadFile (filepath string) {

    file, err := os.Open(filepath)
    check(err)
    defer file.Close()

    // Reading from a file using reader.
    reader := bufio.NewReader(file)
    var line string
    var cnt = 1
    for {
        line, err = reader.ReadString('\n')
        if ( line == "" || ( err != nil && err != io.EOF ) ) {
            break
        }
        // As the line contains newline "\n" character at the end, we could remove it.
        line = line[:len(line)-1]

        fmt.Printf("Line %d : [" + line + "], Length : [%d]\n", cnt, len(line))
        cnt++
    }
}

func main() {

    ReadFile("/tmp/algo.txt")
}

Output

Line 1 : [Merge Sort], Length : [10]
Line 2 : [QuickSort], Length : [9]
Line 3 : [Depth First Search], Length : [18]
Line 4 : [Breadth First Search], Length : [20]
Line 5 : [N Queens Problem], Length : [16]
Line 6 : [Matrix Chain Multiplication], Length : [27]


Below golang program reads a file line by line using Scanner that has an easy interface for reading text delimited by newline character.

  • Scanning operation stops when it encounters EOF or an I/O error.
  • In the below example we read the content of the below file using Scanner.scan ( ) function.
         $ cat /tmp/must_watch.txt
         Breaking Bad 
         Better Call Saul
         Game Of Thrones
         Brooklyn 99
         Dark
      

Go ( Golang ) : Reading a file line by line using scanner

package main

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

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func ReadFile (filepath string) {

    file, err := os.Open(filepath)

    check(err)
    defer file.Close()

    // Reading from a file using scanner.
    scanner := bufio.NewScanner(file)
    var line string
    var cnt = 1 
    for scanner.Scan() {
        line = scanner.Text()
        fmt.Printf("Line %d : [" + line + "], Length : [%d]\n", cnt, len(line))
        cnt++
    }
}

func main() {

    ReadFile("/tmp/must_watch.txt")
}

Output

Line 1 : [Breaking Bad], Length : [12]
Line 2 : [Better Call Saul], Length : [16]
Line 3 : [Game Of Thrones], Length : [15]
Line 4 : [Brooklyn 99], Length : [11]
Line 5 : [Dark], Length : [4]


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.