forked from wcharczuk/go-chart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileutil.go
49 lines (44 loc) · 875 Bytes
/
fileutil.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
package chart
import (
"bufio"
"io"
"os"
)
// ReadLines reads a file and calls the handler for each line.
func ReadLines(filePath string, handler func(string) error) error {
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
err = handler(line)
if err != nil {
return err
}
}
return nil
}
// ReadChunks reads a file in `chunkSize` pieces, dispatched to the handler.
func ReadChunks(filePath string, chunkSize int, handler func([]byte) error) error {
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
chunk := make([]byte, chunkSize)
for {
readBytes, err := f.Read(chunk)
if err == io.EOF {
break
}
readData := chunk[:readBytes]
err = handler(readData)
if err != nil {
return err
}
}
return nil
}