-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.go
60 lines (56 loc) · 1.4 KB
/
file.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
56
57
58
59
60
package aoc
import (
"bufio"
"log"
"os"
"strconv"
"strings"
)
// ReadFile reads the contents of the file and returns a slice of strings.
func ReadFile(fileName string, testing ...bool) []string {
if len(testing) > 0 && testing[0] {
fileName = strings.Replace(fileName, ".txt", "_test.txt", 1)
}
file, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var text []string
for scanner.Scan() {
text = append(text, scanner.Text())
}
file.Close()
return text
}
// ReadFileAsInteger reads the contents of the file and returns a slice of integers.
func ReadFileAsInteger(fileName string, testing ...bool) []int {
if len(testing) > 0 && testing[0] {
fileName = strings.Replace(fileName, ".txt", "_test.txt", 1)
}
file, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var text []int
for scanner.Scan() {
converted, _ := strconv.Atoi(scanner.Text())
text = append(text, converted)
}
file.Close()
return text
}
// ReadFileAsString reads the contents of the file and returns a string.
func ReadFileAsString(fileName string, testing ...bool) string {
if len(testing) > 0 && testing[0] {
fileName = strings.Replace(fileName, ".txt", "_test.txt", 1)
}
file, err := os.ReadFile(fileName)
if err != nil {
log.Fatal(err)
}
return string(file)
}