commit e4dba73017a8d5c4a5022f51140930e5c033d71b Author: Nicolas H. Date: Sat Feb 28 19:55:17 2026 +0100 inital commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b883f1f --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.exe diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..00da199 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module gobook/wordcount + +go 1.25.0 diff --git a/main.go b/main.go new file mode 100644 index 0000000..8a57b65 --- /dev/null +++ b/main.go @@ -0,0 +1,38 @@ +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) +}