-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
98 lines (74 loc) · 1.85 KB
/
Copy pathmain.go
File metadata and controls
98 lines (74 loc) · 1.85 KB
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
package main
// This program read text files from given directory and prints the number of uniq symbols from them
import (
"fileScanner/letterStorage"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sync"
)
const maxWorkingGoroutines = 100
func main() {
if len(os.Args) < 2 {
panic("err: no path")
}
path := os.Args[1]
fileInfo, err := os.Stat(path)
if os.IsNotExist(err) {
panic("err: path not exist")
}
if !fileInfo.IsDir() {
panic("err: is not dir")
}
lettersChannel := make(chan letterStorage.LetterStorage)
semaphore := make(chan int, maxWorkingGoroutines)
wgForWalkFunc := sync.WaitGroup{}
walkFunc := getWalkFunc(lettersChannel, &wgForWalkFunc, semaphore)
wgForPrintResult := sync.WaitGroup{}
wgForPrintResult.Add(1)
go printResult(lettersChannel, &wgForPrintResult)
filepath.Walk(path, walkFunc)
wgForWalkFunc.Wait()
close(lettersChannel)
wgForPrintResult.Wait()
}
func printResult(lettersChannel chan letterStorage.LetterStorage, wg *sync.WaitGroup) {
defer wg.Done()
resultMap := letterStorage.New()
for e := range lettersChannel {
resultMap.Join(e)
}
fmt.Println(resultMap.ToString())
}
func getWalkFunc(lettersChannel chan letterStorage.LetterStorage, wg *sync.WaitGroup, semaphore chan int) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
wg.Add(1)
semaphore <- 0
go func() {
defer wg.Done()
defer func() { <-semaphore }()
if info.IsDir() {
return
}
fileBytes, err := ioutil.ReadFile(path)
checkErr(err)
letters := letterStorage.New()
fileString := string(fileBytes)
for _, ch := range fileString {
letter := string(ch)
if letter == " " || letter == "\n" || letter == "\r" {
continue
}
letters.Add(letter)
}
lettersChannel <- letters
}()
return nil
}
}
func checkErr(err error) {
if err != nil {
panic(err.Error())
}
}