๐Ÿ“ฆ fghpdf / X-largest

๐Ÿ“„ read_file.go ยท 38 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38package topx

import (
	"bufio"
	"os"
	"strconv"
	"strings"
)

// readSingleFile read single file line by line
func readSingleFile(fileName string) ([]*Record, error) {
	// open file
	file, err := os.Open(fileName)
	if err != nil {
		return nil, err
	}

	// init scanner
	scanner := bufio.NewScanner(file)

	// scan file line by line
	scanner.Split(bufio.ScanLines)

	// scan into records
	records := make([]*Record, 0)
	for scanner.Scan() {
		text := strings.Split(scanner.Text(), " ")
		identifier := text[0]
		count, _ := strconv.ParseInt(text[1], 10, 64)
		records = append(records, &Record{identifier, count})
	}

	// close file
	file.Close()

	return records, nil
}