Quick actions

cmd+k|ctrl+k

Navigation

Languages

Strings / Read file line by line / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-03-26T09:39:25Z

Updated

2019-03-26T09:39:25Z

package main

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

func IterLinesInFile(filePath string, process func (s string) bool) error {
    file, err := os.Open(filePath)
    if err != nil {
        return err
    }
    defer file.Close()
    scanner := bufio.NewScanner(file)
    // Scan() reads next line and returns false when reached end or error
    for scanner.Scan() {
        line := scanner.Text()
        if !process(line) {
          return nil
        }
        // process the line
    }
    // check if Scan() finished because of error or because it reached end of file
    return scanner.Err()
}

func main() {
  nLines := 0
  IterLinesInFile("main.go", func(s string) bool {
    nLines++
    return true
  })
  fmt.Printf("%d lines in 'main.go'\n", nLines)
}
INFO