typeline
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
char cmd[200];
char tokenOne[20];
char tokenTwo[20];
char tokenThree[20];
char tokenFour[20];
int numberOfTokens = 0;
int main(void)
{
void typeline(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(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,"typeline") == 0)
{
typeline(tokenTwo,tokenThree);
}
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;
}
if(( strcmp(tokenOne,"exit") == 0 ) && (numberOfTokens == 1))
{
break;
}
}
return(0);
}
void typeline(char *option,char *fname)
{
int lineCount = 0;
char ch = '\0';
int handle = 0;
int lineNumber = 0;
int numberOne = 0;
handle = open(fname,O_RDONLY);
if(handle == -1)
{
printf("Error While Opening '%s' File !!!\n",fname);
return;
}
lineNumber = atoi(option);
while(read(handle,&ch,1))
{
if(ch == '\n')
{
lineCount++;
}
}
if(strcmp(option,"a") == 0)
{
lseek(handle,SEEK_SET,0);
printf("\nDisplaying All Lines Of '%s' File\n\n",fname);
while(read(handle,&ch,1))
{
printf("%c",ch);
}
printf("\n-----------------------------------------------------------------------\n");
}
else if(lineNumber >= 0)
{
lseek(handle,SEEK_SET,0);
printf("\nDisplaying %d Lines Of '%s' File \n\n",lineNumber,fname);
while(read(handle,&ch,1))
{
if(ch == '\n')
{
numberOne++;
}
if(numberOne == lineNumber)
{
break;
}
printf("%c",ch);
}
printf("\n-----------------------------------------------------------------------\n");
}
else if(lineNumber < 0)
{
lseek(handle,SEEK_SET,0);
printf("\nDisplaying Last %d Lines Of '%s' File\n\n",-lineNumber,fname);
numberOne = 0;
lineCount = lineCount + lineNumber;
while(read(handle,&ch,1))
{
if(ch == '\n')
{
numberOne++;
}
if(numberOne == lineCount)
{
break;
}
}
while(read(handle,&ch,1))
{
printf("%c",ch);
}
printf("\n-----------------------------------------------------------------------\n");
}
}