C program to mimic wc command in UNIX

  • Thread starter Thread starter Gagan A
  • Start date Start date
  • Tags Tags
    Program Unix
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 16K views
Gagan A
Messages
19
Reaction score
0
I did it the following way. The number of characters and lines are coming out fine, but the words are usually more than the actual given by wc.

#include<stdio.h>
int main()
{
FILE *fp;
int words=0,chars=0,lines=0;
char prev,curr; //prev variable is included to exclude multiple spaces.
fp=fopen("input.txt","r");
while((fscanf(fp,"%c",&curr))!=EOF)
{
chars++;
if (curr=='\n') lines++;
if ((curr==' ' && prev!=' ') || (curr=='\n' && prev!='\n')) words++; //prev variable comes into play here. if the current char is a space and the previous was also a space then it should not be counted.
prev=curr;
}
printf("%d %d %d\n",chars,lines,words);
return 0;
}
 
Last edited:
Physics news on Phys.org
Use isspace() declared in ctype.h

HiHo!

The mistake is that you have not included the other whitespace characters
(e.g., '\t' and '\r') as tokens that delimit a word.
So, instead of (curr==' ' && prev!=' ') || (curr=='\n' && prev!='\n'), you
should use those is*-functions (e.g. isspace()) declared in ctype.h.

Regards,
Eus
 
Flawed algorithm

HiHo!

Oh, one more thing, you have not considered a test case like this one below.
people<SPACE><ENTER>people.
wc will count that as two words but yours will count that as three words.

Regards,
Eus