/
fileutil.go
103 lines (95 loc) · 2.36 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Package fileutil provides functions for doing things with files, like reading them
// line by line, etc
package fileutil
import (
"bufio"
"crypto/rand"
"encoding/hex"
"fmt"
"os"
"path/filepath"
)
// ReadLinesChannel reads a text file line by line into a channel.
//
// c, err := fileutil.ReadLinesChannel(fileName)
// if err != nil {
// log.Fatalf("readLines: %s\n", err)
// }
// for line := range c {
// fmt.Printf(" Line: %s\n", line)
// }
//
// nil is returned (with the error) if there is an error opening the file
//
func ReadLinesChannel(filePath string) (<-chan string, error) {
c := make(chan string)
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
go func() {
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
c <- scanner.Text()
}
close(c)
}()
return c, nil
}
// ReadLinesSlice reads a text file line by line into a slice of strings.
// Not recommended for use with very large files due to the memory needed.
//
// lines, err := fileutil.ReadLinesSlice(filePath)
// if err != nil {
// log.Fatalf("readLines: %s\n", err)
// }
// for i, line := range lines {
// fmt.Printf(" Line: %d %s\n", i, line)
// }
//
// nil is returned if there is an error opening the file
//
func ReadLinesSlice(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
// WriteLinesSlice writes the given slice of lines to the given file.
func WriteLinesSlice(lines []string, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(w, line)
}
return w.Flush()
}
// Exists returns whether or not the given file or directory exists
func Exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// TempFileName generates a temporary filename for use in testing or whatever
func TempFileName(prefix, suffix string) string {
randBytes := make([]byte, 16)
rand.Read(randBytes)
return filepath.Join(os.TempDir(), prefix+hex.EncodeToString(randBytes)+suffix)
}