Exercise: Working with Files

Test your coding skills on working with files.


In this exercise, your challenge is to expand the word counter wc tool to read data from files in addition to STDIN.

Problem Statement

The current version of the word counter tool wc, which we developed in the “First Command-line Program in Go” chapter, only works with data coming from the standard input STDIN. In this exercise, you’ll expand it to allow it to read data from files.

Coding Challenge

Expand the main function to verify whether the user provided a file name argument in addition to any flags. In this case, read the data from this file instead of STDIN. If the user did not provide a file name, read data from STDIN as usual.

Take some time to figure out the smartest way to solve this problem. Start from the wc implementation at the end of the “First Command-line Program” chapter.

If you feel stuck, refer to Go’s documentation for flag or os packages. If you still need help, check the solution review in the next lesson. Good luck!

> Note: If you’re looking for an extra challenge, allow the user to specify more than one file and print the count for each file, followed by the file name.

Get hands-on with 1200+ tech skills courses.