Skip to content

Instantly share code, notes, and snippets.

@andreagrandi
Created August 21, 2014 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreagrandi/544affe4567ba6f29f89 to your computer and use it in GitHub Desktop.
Save andreagrandi/544affe4567ba6f29f89 to your computer and use it in GitHub Desktop.
Read a text file and print its lines in Go
package main
import (
"flag"
"fmt"
"io/ioutil"
"strings"
)
var fileName = flag.String("f", "", "Filename to be read")
func main() {
flag.Parse()
content, err := ioutil.ReadFile(*fileName)
if err != nil {
panic(err)
}
lines := strings.Split(string(content), "\n")
// First parameter returned by the next statement is a counter.
// If you don't need it, you use _ as return variable.
for _, line := range lines {
fmt.Println(line)
}
}
@andreagrandi
Copy link
Author

Example: go run text_file_reader.go -f test.txt

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