We have all at some point used the Linux wc command line tool while developing
something, but have you ever thought of making it?
Today we will be tackling
how to build our own version of wc offering most of the functionality:
Counting lines
Counting words
Counting characters
Measuring the number of bytes
Using the beloved Golang.
Left off
start by initilizing your project and create a
main.go file as our entry point:
Step 1: Counting Bytes
starting off we will need to recived command line argument from our program, so
we will utilize the flag package which is helpfull in parsing CLI argumnets:
Now, we are going to open the specified file path, pass the file as a reader
for a function that calculates it’s size and returns an int representing the
number of bytes.
And now we will modifiy our main function to check if the user has requested
to show the size of bytes using the -c flag or not.
Until now are not printing the file path to the user as it’s done in the
original wc. that is because the user might not pass a file path and instead
pass the file contents directly through piping:
This is the reason also we are treating the file as a reader while we might have just use the file.Stat() struct.
This is something we will tackle in the final step don’t worry.
Step 2: Counting Lines
Now, we will modify our init function to accept the -l option.
And we will add the function that calculates the number of lines from a reader
on thing left is the modify our main to show the number of lines on demand.
Step 3: Counting Words
We will wake the same path as we did before:
modify init to recieve the CLI argument -w
create the function the calculates the number of words
modify main to show the output on demand
Good job, we are half way there!
On to..
Step 4: Counting Characters
You already guessed it:
Step 5: Empty as void
In this scennario we will be handling when the user doesn’t pass any
arguments, we will by default show all output.
This can be done easly by a simple if statement:
The grand finale
Until now, we didn’t ouput the name of the file path passed to the CLI, because
we kept in mind this step.
We will add a condition to check if the user has passed a file path or is piping
the file contents directly to our CLI:
If the user has passed a file path we will read the file, pass it to our
program because it already implements the ReadSeaker interface, and will
output the path at the end.
If the user piped the file contents directly, we will turn the contents into a
reader and we will not output the file path ” as it is done in the original
wc”, because there is no way of knowing the original file path.
CleanUp
Our code looks a little bit clunky now, so we can extract some functioanlity
into a utils.go file which will contain specficially the calculate
functions.