Files
wordcount/main.go
2026-02-28 19:55:17 +01:00

39 lines
561 B
Go

package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func main() {
if len(os.Args) < 2 {
log.Println("need to provide filename!")
os.Exit(1)
}
file, err := os.Open(os.Args[1])
if err != nil {
os.Exit(1)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var wordCount int
for scanner.Scan() {
// This is done for each line of the file.
words := strings.Fields(scanner.Text())
wordCount += len(words)
}
if scanner.Err() != nil {
log.Println(scanner.Err())
os.Exit(1)
}
fmt.Printf("Found %d words", wordCount)
}