Quick actions

cmd+k|ctrl+k

Navigation

Languages

Files and I/O / Reading files / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-08-30T00:28:04Z

Updated

2019-08-30T00:28:04Z

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

// ReadLines reads all lines from a file
func ReadLines(filePath string) ([]string, error) {
	file, err := os.OpenFile(filePath, os.O_RDONLY, 0666)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	res := make([]string, 0)
	for scanner.Scan() {
		line := scanner.Text()
		res = append(res, line)
	}
	if err = scanner.Err(); err != nil {
		return nil, err
	}
	return res, nil
}

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