Skip to content

Instantly share code, notes, and snippets.

@derlin
Created August 16, 2016 09:20
Show Gist options
  • Save derlin/129f0a5c06b3f5221c6d22e414608803 to your computer and use it in GitHub Desktop.
Save derlin/129f0a5c06b3f5221c6d22e414608803 to your computer and use it in GitHub Desktop.
Golang example: read a file line by line.
package main
import (
"fmt"
"os"
"bufio"
)
func ReadLineByLine(filepath string, out chan string) {
defer close(out)
file, err := os.Open(filepath)
if err != nil {
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
lines := 0
for scanner.Scan() {
out <- scanner.Text()
lines++
}
}
func main() {
argc := len(os.Args)
if argc < 2 {
fmt.Printf("usage: %s <json file>\n", os.Args[0])
os.Exit(1)
}
c := make(chan string)
go ReadLineByLine(os.Args[1], c)
for running := true; running; {
var s string;
select {
case s, running = <- c:
fmt.Println(s)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment