Quick actions

cmd+k|ctrl+k

Navigation

Languages

Strings / Read file line by line / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-03-26T10:12:49Z

Updated

2019-03-26T10:12:49Z

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"strings"
)

// ReadFileAsLines reads a file and splits it into lines
func ReadFileAsLines(path string) ([]string, error) {
	d, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	s := string(d)
	lines := strings.Split(s, "\n")
	return lines, nil
}

func main() {
	path := "main.go"
	lines, err := ReadFileAsLines(path)
	if err != nil {
		log.Fatalf("ReadFileAsLines() failed with '%s'\n", err)
	}
	fmt.Printf("There are %d lines in '%s'\n", len(lines), path)
}
INFO