Simulation of Unix Commands 4

SIMULATION OF UNIX COMMANDS – Word Count (wc)

// 4. wc command
#include<stdio.h>
int wc,lc,cc;

load(fp1,g)
FILE *fp1;
char g[];
{
int n;
for(n=0;(g[n]=getc(fp1))!=EOF;n++)
if(g[n]==’\n’)
 {
g[n]=’\0′;
return 1;
}
return 0;
}

count(g)
char g[];
{
int n;
for(n=0;g[n]!=’\0′;n++)
{
lc++;
if(g[n]!=’\t’ && g[n]!=’ ‘ )
cc++;
if( (g[n]==’\t’ && g[n+1]!=’\t’ )||(g[n]==’ ‘ && g[n+1]!=’ ‘ ) )
wc++;
}
}

// main prrogram
main(int argc, char * argv[] )
{
FILE *fp;
int i;
char a[100];
if(argc!=2)
{
printf(“Usage error”);
return;
}
fp = fopen(argv[1],”r”);
if(fp==NULL)
{
printf(“File opening error”);
return;
}
i=load(fp,a);
while(i==1)
{
count(a);
i=load(fp,a);
}
printf(“\nWord Count : %d”, wc);
printf(“\nLine Count : %d”, lc);
printf(“\nCharacter Count : %d”, cc);
close(fp);
}