diff --git a/cmd/wc-go/main.go b/cmd/wc-go/main.go index 5e57081..7652cd6 100644 --- a/cmd/wc-go/main.go +++ b/cmd/wc-go/main.go @@ -72,8 +72,66 @@ func main() { if len(goopt.Args) == 0 { fmt.Println(goopt.Help()) } else { + if !*fWords && !*fChars && !*fLines && !*fBytes && !*fMaxLineLength { + *fWords = true + *fChars = false + *fLines = true + *fBytes = true + *fMaxLineLength = false + } + var TotalCounts wc.Counter for _, a := range goopt.Args { - wc.Count(a, *fWords, *fChars, *fLines, *fBytes, *fMaxLineLength) + count, err := wc.Count(a, *fWords, *fChars, *fLines, *fBytes, *fMaxLineLength) + if err == nil { + TotalCounts.Lines += count.Lines + TotalCounts.Bytes += count.Bytes + TotalCounts.Words += count.Words + TotalCounts.Chars += count.Chars + TotalCounts.MaxLineLength += count.MaxLineLength + if *fLines { + fmt.Printf("%d", count.Lines) + } + fmt.Printf(" ") + if *fWords { + fmt.Printf("%d", count.Words) + } + fmt.Printf(" ") + if *fChars { + fmt.Printf("%d", count.Chars) + } + fmt.Printf(" ") + if *fBytes { + fmt.Printf("%d", count.Bytes) + } + fmt.Printf(" ") + if *fMaxLineLength { + fmt.Printf("%d", count.MaxLineLength) + } + fmt.Printf(" %s\n", a) + } + + } + if len(goopt.Args) > 1 { + if *fLines { + fmt.Printf("%d", TotalCounts.Lines) + } + fmt.Printf(" ") + if *fWords { + fmt.Printf("%d", TotalCounts.Words) + } + fmt.Printf(" ") + if *fChars { + fmt.Printf("%d", TotalCounts.Chars) + } + fmt.Printf(" ") + if *fBytes { + fmt.Printf("%d", TotalCounts.Bytes) + } + fmt.Printf(" ") + if *fMaxLineLength { + fmt.Printf("%d", TotalCounts.MaxLineLength) + } + fmt.Println(" total") } } } diff --git a/pkg/wc/counter.go b/pkg/wc/counter.go index 129804d..016600f 100644 --- a/pkg/wc/counter.go +++ b/pkg/wc/counter.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "os" + "runtime" "unicode/utf8" ) @@ -17,25 +18,18 @@ type Counter struct { MaxLineLength int64 } -func Count(filename string, cw, cc, cl, cb, mll bool) { - if !cw && !cc && !cl && !cb && !mll { - cw = true - cc = false - cl = true - cb = true - mll = false - } +func Count(filename string, cw, cc, cl, cb, mll bool) (Counter, error) { file, err := os.Open(filename) if err != nil { fmt.Println(err) - return + return Counter{}, err } defer file.Close() processLine := cw || cc var c = &Counter{} - numWorkers := 2 //runtime.NumCPU() + numWorkers := runtime.NumCPU() if cl && !processLine { c.Lines = CountLines(file, numWorkers) @@ -48,27 +42,11 @@ func Count(filename string, cw, cc, cl, cb, mll bool) { fi, err := file.Stat() if err != nil { fmt.Println(err) - return + return Counter{}, err } c.Bytes = fi.Size() } - - if cl { - fmt.Printf("%d ", c.Lines) - } - if cw { - fmt.Printf("%d ", c.Words) - } - if cc { - fmt.Printf("%d ", c.Chars) - } - if cb { - fmt.Printf("%d ", c.Bytes) - } - if mll { - fmt.Printf("%d ", c.MaxLineLength) - } - fmt.Printf("%s\n", filename) + return *c, nil } func CountLines(file *os.File, numWorkers int) int64 {