search
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
int numberOfTokens = 0;
char cmd[100];
char tokenOne[20];
char tokenTwo[20];
char tokenThree[20];
char tokenFour[20];
int main(void)
{
void search(char *,char *,char *);
while(1)
{
printf("MyShell$] ");
fgets(cmd,sizeof(cmd),stdin);
numberOfTokens = sscanf(cmd,"%s %s %s %s",tokenOne,tokenTwo,tokenThree,tokenFour);
switch(numberOfTokens)
{
case 1:
if(strcmp(tokenOne,"exit") == 0)
{
exit(0);
}
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(fork() == 0)
{
execlp(tokenOne,tokenOne,tokenTwo,tokenThree,NULL);
}
wait(0);
break;
case 4:
if(strcmp(tokenOne,"search") == 0)
{
search(tokenTwo,tokenThree,tokenFour);
}
else if(fork() == 0)
{
execlp(tokenOne,tokenOne,tokenTwo,tokenThree,NULL);
}
wait(0);
break;
}
}
return(0);
}
void search(char *option, char *pattern,char *fname)
{
int handle;
int i = 0;
int count = 0;
handle = open(fname,O_RDONLY);
char data[200] = {'\0'};
char ch;
char *ptr = NULL;
if(handle == -1)
{
printf("\nError While Opening %s File !!!\n",fname);
exit(-1);
}
if((strcmp(option,"f") == 0) || (strcmp(option,"F") == 0))
{
i = 0;
while(read(handle,&ch,1))
{
data[i] = ch;
i++;
if(ch == '\n')
{
data[i] = '\0';
if(strstr(data,pattern) != NULL)
{
printf("First Occurance Of \" %s \" In Line :\n%s",pattern,data);
close(handle);
break;
}
i = 0;
}
}
}
else if((strcmp(option,"A") == 0) || (strcmp(option,"a") == 0))
{
i = 0;
while(read(handle,&ch,1))
{
data[i] = ch;
i++;
if(ch == '\n')
{
data[i] = '\0';
if(strstr(data,pattern) != NULL)
{
printf("%s",data);
}
i = 0;
}
}
}
else if((strcmp(option,"C") == 0) || strcmp(option,"c") == 0)
{
i = 0;
count = 0;
while(read(handle,&ch,1))
{
data[i] = ch;
i++;
if(ch == '\n')
{
data[i] = '\0';
ptr = data;
while((ptr = strstr(ptr,pattern)) != NULL)
{
ptr++;
count++;
}
i = 0;
}
}
printf("\n%s Found %d Times\n",pattern,count);
}
close(handle);
}