Skip to content

Instantly share code, notes, and snippets.

@kjk
Last active July 12, 2020 22:31
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 kjk/2f493d47f6d8bb328a3a86e4bbefff9c to your computer and use it in GitHub Desktop.
Save kjk/2f493d47f6d8bb328a3a86e4bbefff9c to your computer and use it in GitHub Desktop.
Files and I/O (made with https://codeeval.dev)
// :collection Essential Go
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
)
func main() {
// :show start
path := "read file into lines.go"
f, err := os.Open(path)
if err != nil {
log.Fatalf("os.Open() failed with %s\n", err)
}
defer f.Close()
d, err := ioutil.ReadAll(f)
if err != nil {
log.Fatalf("ioutil.ReadAll() failed with '%s'\n", err)
}
lines := bytes.Split(d, []byte{'\n'})
fmt.Printf("File '%s' has %d lines\n", path, len(lines))
// :show end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment