Skip to content

Instantly share code, notes, and snippets.

@freeformz
Last active December 12, 2015 01:08
Show Gist options
  • Save freeformz/4688206 to your computer and use it in GitHub Desktop.
Save freeformz/4688206 to your computer and use it in GitHub Desktop.
package utils
import "fmt"
func main() {
for line := range FileLineChannel('/etc/hosts') {
fmt.Println(line)
}
}
package utils
import (
"log"
"bufio"
"io"
"os"
)
func FileLineChannel(fpath string) (<-chan string) {
c := make(chan string)
go func(fpath string, cs chan<- string) {
defer close(cs)
file, err := os.Open(fpath)
if err == nil {
defer file.Close()
buf := bufio.NewReader(file)
for {
line, err := buf.ReadString('\n')
switch err {
case io.EOF: break
case nil: cs <- line
default: log.Fatal(err)
}
}
}
}(fpath, c)
return c
}
@jehiah
Copy link

jehiah commented Feb 1, 2013

I think you need to move the cs <- line above your switch as otherwise if the file ends without a newline, you won't send the last line into your channel. (the case io.EOF will hit first).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment