-
-
Save bbrodriges/b6ac1cad4866528cced72b8881dbb221 to your computer and use it in GitHub Desktop.
word counter
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 ( | |
"bufio" | |
"flag" | |
"fmt" | |
"log" | |
"os" | |
) | |
func main() { | |
filename := flag.Arg(0) | |
word := flag.Arg(1) | |
if filename == "" || word == "" { | |
log.Fatal("filename and word arguments required") | |
} | |
fd, err := os.Open(filename) | |
if err != nil { | |
log.Fatalf("cannot open file: %s", err) | |
} | |
defer fd.Close() | |
scanner := bufio.NewScanner(fd) | |
scanner.Split(bufio.ScanWords) | |
var wordCount int | |
for scanner.Scan() { | |
if scanner.Text() == word { | |
wordCount++ | |
} | |
} | |
if err := scanner.Err(); err != nil { | |
log.Fatalf("unexpected scanning error: %s", err) | |
} | |
fmt.Printf(`Word "%s" found in file %d times\n`, word, wordCount) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment