Building a Unix/Linux wc Tool Part III: Adding Support for Word Counting

Jonathan Zihindula
2 min readJun 13, 2024

--

For the quick recap, the first part of this journey was to build a basic wc command line tool supporting only the -c which prints out the byte number of the file. In the second part the goal was to add a support for -l command for counting the number of line in a file. In this third part, I’m moving one step forward by adding the -w commad for counting the number of words on a file.

  1. Building unix/linux wc tool part I: https://medium.com/@jonathanzihindula95/building-unix-linux-wc-part-i-bc30babaeb70
  2. Building unix/linux wc tool part II: https://medium.com/@jonathanzihindula95/building-unix-linux-wc-part-ii-line-counter-c7204d682812

Words counter function

I created a countWords function that opens a specified file, counts the number of words in it using a scanner, and prints the word count along with the file name. It handles errors in file opening by panicking and ensures the file is closed properly after processing.

func countWords(fileName string) {
file, err := os.Open(fileName)
if err != nil {
panic(err.Error())
}

defer file.Close()
wordCounter := 0
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
wordCounter++
}

fmt.Println(wordCounter, fileName)
}

After creating this function, I had to add the -w flag and process the file accordingly when this flag is used.

func main() {
...go
wordCounter := flag.String("w", "", "Flag to get the file word counter")
flag.Parse()

...

if *wordCounter != "" {
ProcessFile(wordCounter, countWords)
}

}

In this code, if the -w flag is passed, then the processFile function is called. It also receives the countWords function as a callback.

Thanks for reading! Stay tuned for the next step, where the goal will be to add support for the -m flag for counting the number of characters in a file. You can find the codebase of the current progress here.

--

--