Created
December 17, 2021 20:04
-
-
Save synaptic-cleft/9f8a439ca4902bdfb246c70f3f2e7bc5 to your computer and use it in GitHub Desktop.
Word count in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"bufio" | |
"strings" | |
) | |
func main() { | |
file, error := os.Open("/path/to/file") | |
if error != nil { | |
fmt.Println("Could not read file.") | |
os.Exit(1) | |
} | |
defer file.Close() | |
scanner := bufio.NewScanner(file) | |
words := 0 | |
for scanner.Scan() { | |
line := strings.Fields(scanner.Text()) | |
words += len(line) | |
} | |
fmt.Printf("File currently contains %d words.\n", words) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment