M.E. Irizarry-Gelpí

Physics impostor. Mathematics interloper. Husband. Father.

Reading Files in Go


Here is a simple way to read the lines of a text file in Go without using the io package. You will need the fmt package. Create a file read.go with contents

package main

import "fmt"

func main() {
    lines := make([]string, 0)
    var line string
    var err error

    for {
        _, err = fmt.Scanln(&line)
        if err != nil {
            break
        }
        lines = append(lines, line)
    }

    fmt.Println(len(lines))
}

Now consider the file text.txt with contents

line1
line2
line3
line4

At the command line, use

cat ./text.txt | go run read.go

The output is 4.

Similarly, we can read an array from a line. This is how I figured out how to do it; there is most likely a better way of doing this. Start with a file array.go:

package main

import "fmt"

func main() {
    x := make([]int, 0)
    var y int
    var err error

    for {
        _, err = fmt.Scan(&y)
        if err != nil {
            break
        }

        x = append(x, y)
    }

    fmt.Println(x)
}

and a file nums.txt:

1 2 3 4 5 6 7 8 9 10 11

At the command line, use

cat ./nums.txt | go run array.go

The output is [1 2 3 4 5 6 7 8 9 10 11].