-
Notifications
You must be signed in to change notification settings - Fork 14
/
wc.go
59 lines (51 loc) · 911 Bytes
/
wc.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
package main
import (
"fmt"
"io"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Please provide a filename")
os.Exit(1)
}
filename := os.Args[1]
_, err := os.Stat(filename)
if err != nil {
fmt.Printf("Error on file %s: %s\n", filename, err)
os.Exit(1)
}
f, err := os.Open(filename)
if err != nil {
fmt.Println("Cannot open file:", err)
os.Exit(-1)
}
defer f.Close()
chars := countChars(f)
filename = filename + ".Count"
f, err = os.Create(filename)
if err != nil {
fmt.Println("os.Create:", err)
os.Exit(1)
}
defer f.Close()
writeNumberOfChars(f, chars)
}
func countChars(r io.Reader) int {
buf := make([]byte, 16)
total := 0
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
return 0
}
if err == io.EOF {
break
}
total = total + n
}
return total
}
func writeNumberOfChars(w io.Writer, x int) {
fmt.Fprintf(w, "%d\n", x)
}