Added support for w flag

main
oabrivard 2 years ago
parent b5619c98d6
commit 944f21ec5c

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"slices"
) )
func byteCounter(f *os.File) { func byteCounter(f *os.File) {
@ -23,11 +24,36 @@ func lineCounter(f io.Reader) {
lineSep := []byte{'\n'} lineSep := []byte{'\n'}
for { for {
c, err := f.Read(buf) c, err := f.Read(buf) // c==0 if EOF
switch {
case err == io.EOF:
fmt.Println(count)
return
case err != nil:
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
count += bytes.Count(buf[:c], lineSep) count += bytes.Count(buf[:c], lineSep)
}
}
func wordCounter(f io.Reader) {
buf := make([]byte, 32*1024)
count := 0
wordSep := []byte{' ', '\t', '\n', '\r', '\f', '\v'}
inWord := false
for {
c, err := f.Read(buf)
switch { switch {
case err == io.EOF: case err == io.EOF:
if inWord {
count++
}
fmt.Println(count) fmt.Println(count)
return return
@ -35,6 +61,17 @@ func lineCounter(f io.Reader) {
fmt.Fprintf(os.Stderr, "error: %v\n", err) fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
for _, b := range buf[:c] {
if slices.Contains(wordSep, b) {
if inWord {
count++
}
inWord = false
} else {
inWord = true
}
}
} }
} }
@ -42,6 +79,7 @@ func main() {
cFlag := flag.Bool("c", false, "print the byte counts") cFlag := flag.Bool("c", false, "print the byte counts")
lFlag := flag.Bool("l", false, "print the line counts") lFlag := flag.Bool("l", false, "print the line counts")
wFlag := flag.Bool("w", false, "print the word counts")
flag.Parse() flag.Parse()
fileName := flag.Arg(0) fileName := flag.Arg(0)
@ -63,5 +101,7 @@ func main() {
byteCounter(f) byteCounter(f)
case *lFlag: case *lFlag:
lineCounter(f) lineCounter(f)
case *wFlag:
wordCounter(f)
} }
} }

Loading…
Cancel
Save