Last active
July 12, 2020 22:31
-
-
Save kjk/2f493d47f6d8bb328a3a86e4bbefff9c to your computer and use it in GitHub Desktop.
Files and I/O (made with https://codeeval.dev)
This file contains 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
// :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