-
Notifications
You must be signed in to change notification settings - Fork 2
/
fileio.go
51 lines (40 loc) · 1.03 KB
/
fileio.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
package main
import (
"bufio"
"fmt"
"os"
)
// Open reads a file and returns erows representing each line
func Open(fileName string) ([]ERow, error) {
r, err := os.Open(fileName)
if err != nil {
return nil, fmt.Errorf("error opening file %s: %w", fileName, err)
}
defer r.Close()
ret := []ERow{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
ret = append(ret, []rune(scanner.Text()))
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading file %s: %w", fileName, err)
}
return ret, err
}
// Save writes a file to disk
func Save(rows []ERow, filename string) error {
fil, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating file: %s: %w", filename, err)
}
defer fil.Close()
for _, row := range rows {
if _, err := fmt.Fprintf(fil, "%s\n", string(row)); err != nil {
return fmt.Errorf("error writing to file %s: %w", filename, err)
}
}
if err = fil.Close(); err != nil {
return fmt.Errorf("error closing written file: %s: %w", filename, err)
}
return nil
}