count
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
char cmd[100];
char tokenOne[20];
char tokenTwo[20];
char tokenThree[20];
char tokenFour[20];
int numberOfTokens = 0;
void count(char option[],char fname[]);
int main(void)
{
while(1)
{
printf("MyShell$ ");
fgets(cmd,sizeof(cmd),stdin);
numberOfTokens = sscanf(cmd,"%s%s%s%s",tokenOne,tokenTwo,tokenThree,tokenFour);
if(strcmp(tokenOne,"exit") == 0)
{
printf("Exitting...\n\n");
break;
}
switch(numberOfTokens)
{
case 1:
if(fork() == 0)
{
execlp(tokenOne,tokenOne,NULL);
}
wait(0);
break;
case 2:
if(fork() == 0)
{
execlp(tokenOne,tokenOne,tokenTwo,NULL);
}
wait(0);
break;
case 3:
if(strcmp(tokenOne,"count") == 0)
{
count(tokenTwo,tokenThree);
}
else if(fork() == 0)
{
execlp(tokenOne,tokenOne,tokenTwo,tokenThree,NULL);
}
wait(0);
break;
case 4:
if(fork() == 0)
{
execlp(tokenOne,tokenOne,tokenTwo,tokenThree,tokenFour,NULL);
}
wait(0);
break;
default:
break;
}
}
return(0);
}
void count(char option[], char fname[])
{
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
char ch = '\0';
int handle = 0;
handle = open(fname,O_RDONLY);
if(handle == -1)
{
printf("Error While Opening File '%s' !!!\n",fname);
return;
}
while(read(handle,&ch,1))
{
charCount++;
if((ch == ' ') || (ch == '\t'))
{
wordCount++;
}
else if(ch == '\n')
{
wordCount++;
lineCount++;
}
}
if(strcmp(option,"c") == 0)
{
// Character Count
printf("\nNumber OF Character In '%s' File Is %d\n\n",fname,charCount);
}
else if(strcmp(option,"l") == 0)
{
// line count
printf("\nNumber Of Lines In '%s' File Is %d \n\n",fname,lineCount);
}
else if(strcmp(option,"w") == 0)
{
// word count
printf("\nNumber Of Words In '%s' File Is %d\n\n",fname,wordCount);
}
}