Implement simple version of ‘wc’ command of UNIX/Linux in C Language !

wc‘ is a command in UNIX/Linux to count the lines, words and characters from the input that is given to the command. This program is known as “Word Counting” which is a very famous interview question  in an Embedded System Company’s interview. I would suggest you to read the book written by Ritchie to get the complete implementation. The simple code goes here:

#include <stdio.h>

#define IN  1

#define OUT 0

int main( )


int c, nol, now, noc, state;

state = OUT;

nol = now = noc = 0;

 while( (c = getchar( )) != EOF )



if( c == ‘\n’ )


if( c == ‘ ‘ || c == ‘\n’ || c == ‘\t’ )

state = OUT;

else if ( state == OUT )


state = IN;




printf( “%d %d %d\n”, nol, now, noc );


It is left as an exercise to understand how the C program works here. I would suggest you to take a pen and a sheet of paper to trace it line by line.

Author Information:

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.



No Comment

You can post first response comment.

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.