-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
55 lines (47 loc) · 872 Bytes
/
utils.go
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package memory
import (
"bufio"
"math"
"os"
)
func truncateResult(n float64) float64 {
return math.Trunc(n*10) / 10
}
func readLines(s string, n int) ([]string, error) {
f, err := os.Open(s)
if err != nil {
return nil, err
}
defer f.Close()
lines := make([]string, 0, n)
sc := bufio.NewScanner(f)
for i := 0; i < n && sc.Scan(); i++ {
lines = append(lines, sc.Text())
}
return lines, nil
}
func readFirstLine(s string) (string, error) {
f, err := os.Open(s)
if err != nil {
return "", err
}
defer f.Close()
sc := bufio.NewScanner(f)
sc.Scan()
return sc.Text(), nil
}
func readLine(s string, n int) (string, error) {
f, err := os.Open(s)
if err != nil {
return "", err
}
defer f.Close()
var line string
sc := bufio.NewScanner(f)
for i := 0; i < n && sc.Scan(); i++ {
if i == n-1 {
line = sc.Text()
}
}
return line, nil
}