12 August 2010

wc: very simple word count C program

It is a very trivial program that count the words in a file according to some policy.

// wc.c
// auther : mhewedy

#include <stdio.h>
#include <stdlib.h>

int wc(char*);

int main(int argc, char** argv)
{
FILE *fp = NULL;
char buff[100], *fileName = NULL;
int wcnt = 0;

if (argc <2)
{
fprintf(stderr, "Usage: wc <file_name>\n");
exit(1);
}

fileName = argv[1];

if ( (fp = fopen(fileName, "r")) == NULL)
{
perror(fileName);
exit(1);
}

while (!feof(fp))
{
buff[0] = '\0';
fgets(buff, sizeof buff/sizeof(char), fp);
wcnt += wc(buff);
}

fclose(fp);

printf("word count: %i words\n", wcnt);
return 0;
}

/*
Idea of this function taked from the book : Programming in C, thired edition
*/
int wc(char* line)
{
int is_alpha(int ch), wc=0;
int start_word = 1;

while (*line != '\0')
{
if (is_alpha(*line))
{
if (start_word)
{
start_word = 0;
wc++;
}
}else{
start_word = 1;
}
line++;
}
return wc;
}

int is_alpha(int ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}

Post a Comment