Read a file into an array of lines in Go

This is an example Go program which illustrates reading a file line by line.

package main

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

func fileToLines(fileName string) (lines []string, err error) {
        file, err := os.Open(fileName)
        if err != nil {
                return lines, err
        }
        defer file.Close()
        scanner := bufio.NewScanner(file)
        for scanner.Scan() {
                lines = append(lines, scanner.Text())
        }
        return lines, scanner.Err()
}

func main() {
        na := len(os.Args)
        if na < 2 {
                fmt.Fprintf(os.Stderr, "Usage: %s <string> <file1> <file2> ...\n",
                        os.Args[0])
                os.Exit(1)
        }
        string := os.Args[1]
        for n := 2; n < len(os.Args); n++ {
                fileName := os.Args[n]
                lines, err := fileToLines(fileName)
                if err != nil {
                        fmt.Fprintf(os.Stderr, "Error reading %s: %s.\n", fileName, err)
                        continue
                }
                for i, l := range lines {
                        if strings.Contains(l, string) {
                                fmt.Printf("%s:%d: %s\n", fileName, i+1, l)
                        }
                }
        }
}

(download)

The output of the example, run on its own source code,

./rl "main" rl.go

looks like this:

rl.go:1: package main
rl.go:23: func main() {


Copyright © Ben Bullock 2009-2022. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer