I redid my code and it partially works right now. I can use strtok to find the first input in the command line, but cannot get the arguments.
The format is <command> <arg1> <arg2>
So far, I've only implemented 'exit' and 'help'. When I run this code, it compiles fine but I get a segmentation fault. I've placed a couple printf to help debug. One of the problems is that the arguments are not detected/counted.
Here is the output:
************************************************** *
Welcome to O-Shell! A UNIX shell by O Haqqi
Type 'help' for list of commands, 'exit' to exit
************************************************** *
o-shell>exit
exit was entered
There are 0 arguments
Command is exit
Segmentation fault (core dumped)
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main(int argc, char *argv[])
{
char command[50]; //Command line input
//tokens for strtok() funtion
char * com; //Primary command
char * arg1; //First argument of command (usually a file name)
char * arg2; //2nd argument of command (usually a file name)
int args; //Number of arguments entered
printf("************************************************** *\n");
printf("Welcome to O-Shell! A UNIX shell by O Haqqi\n\n");
printf("Type 'help' for list of commands, 'exit' to exit\n");
printf("************************************************** *\n\n");
for(;;)
{
printf("o-shell>"); //user prompts for o-shell
scanf("%s", command); //command line input from user
printf("%s was entered\n", command);
com = strtok(command, " \r\n\t");
args = 0;
arg1 = strtok(NULL, " \r\n\t");
if(arg1) args++; //to see if arguments being tracked
arg2 = strtok(NULL, " \r\n\t");
if(arg2) args++; //to see if arguments being tracked
printf("There are %d arguments\n", args);
printf("Command is %s\n", com);
printf("File1 is %s\n", arg1);
printf("File2 is %s\n", arg2);
if ((strcmp(com,"help")) ==0 || (strcmp(com,"Help")) ==0)
{
printf("\nO-Shell Help Menu:\n");
printf("\nhelp - Print help menu\n");
printf("\nexit - Exit O-Shell\n");
printf("\ntype <file> - Print contents of <file>\n");
printf("\ncopy <file1> <file2> - Copy contents of <file1> to <file2>.");
printf("\n <file2> must be a non-existent file and must be created\n");
printf("\ndelete <file> - Delete <file>\n\n");
}
else if ((strcmp(com,"exit")) ==0 || (strcmp(com,"Exit")) ==0)
{
printf("Exiting O-Shell...Goodbye!\n");
break;
}
else
printf("Invalid command!!! No operation performed...\n");
}
return 0;
}