Created
August 16, 2016 09:20
-
-
Save derlin/129f0a5c06b3f5221c6d22e414608803 to your computer and use it in GitHub Desktop.
Golang example: read a file line by line.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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