-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
94 lines (74 loc) · 1.71 KB
/
main.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
package main
import (
"flag"
"fmt"
"log"
"os"
"strings"
)
func readFile(filename string) (string, error) {
fileData, err := os.ReadFile(filename)
if err != nil {
return "", err
}
return string(fileData), nil
}
func countWords(fileContents string) int {
words := strings.Fields(fileContents)
return len(words)
}
func countLines(fileContents string) int {
lines := strings.Split(fileContents, "\n")
return len(lines) - 1
}
func countCharacters(fileContents string) int {
return len(fileContents)
}
func main() {
// fmt.Println(contents)
linesFlag := flag.Bool("l", false, "Count lines")
wordsFlag := flag.Bool("w", false, "Count words")
charactersFlag := flag.Bool("c", false, "Count characters")
flag.Parse()
files := flag.Args()
var totalLines, totalWords, totalCharacters int
for _, filename := range files {
fileContents, err := readFile(filename)
if err != nil {
log.Println(err)
}
if !*linesFlag && !*wordsFlag && !*charactersFlag {
fmt.Printf("%8d%8d%8d %s\n", countLines(fileContents), countWords(fileContents), countCharacters(fileContents), filename)
continue
}
if *linesFlag {
lines := countLines(fileContents)
totalLines += lines
fmt.Printf("%8d", lines)
}
if *wordsFlag {
words := countWords(fileContents)
totalWords += words
fmt.Printf("%8d", words)
}
if *charactersFlag {
characters := countCharacters(fileContents)
totalCharacters += characters
fmt.Printf("%8d", characters)
}
fmt.Printf(" %s\n", filename)
}
if (len(files) < 2) {
return
}
if *linesFlag {
fmt.Printf("%8d", totalLines)
}
if *wordsFlag {
fmt.Printf("%8d", totalWords)
}
if *charactersFlag {
fmt.Printf("%8d", totalCharacters)
}
fmt.Printf(" total\n")
}