Skip to content

Instantly share code, notes, and snippets.

@sc0Vu
Last active October 9, 2020 07:05
Show Gist options
  • Select an option

  • Save sc0Vu/1eb67a827a47201adc926ed9117c1b51 to your computer and use it in GitHub Desktop.

Select an option

Save sc0Vu/1eb67a827a47201adc926ed9117c1b51 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io"
"log"
"os"
"unicode"
"github.com/pkg/profile"
)
func readbyte(r io.Reader) (rune, error) {
var buf [1]byte
_, err := r.Read(buf[:])
return rune(buf[0]), err
}
func main() {
if len(os.Args) != 2 {
log.Fatal("usage: cmd [text file]")
}
defer profile.Start().Stop()
f, err := os.Open(os.Args[1])
if err != nil {
log.Fatalf("could not open file %q: %v", os.Args[1], err)
}
words := 0
inword := false
for {
r, err := readbyte(f)
if err == io.EOF {
break
}
if err != nil {
log.Fatalf("could not read file %q: %v", os.Args[1], err)
}
if unicode.IsSpace(r) && inword {
words++
inword = false
}
inword = unicode.IsLetter(r)
}
fmt.Printf("%q: %d words\n", os.Args[1], words)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment