Hi everybody. I haven't programmed anything in about 8 years, I've read up a little bit on C and need to write a shell in C. I want to use strtok() to take an input from a user and parse it into the command and its arguments.
for example: copy <file1> <file2> will copy file 2 to file 1, del <file1> will delete a file, etc. The exit command is all I've implemented right now, but even that produces an error when executed...I'm sure I've got a problem with how I've implemented strtok().
I've tried to implement it below, but when I compile it using gcc (no errors/warnings) and try to execute it I get the following output:
o-shell>exit
com = exit
Segmentation fault (core dumped)
Here is the code snippet:
****************************
****************************Code:char command[50]; //Command line input char com[10]; //Primary command char file1[20]; //File affected by command (if necessary) char file2[20]; //2nd file affected by command (if necessary) char *token; //Used for strtok() function for(; { printf("o-shell>"); //user prompts for o-shell scanf("%s", command); //command line input from user //tokenize the command line input using strtok() function //this produces the command as well as any command line arguments while(token != NULL) { token = strtok(command, " "); strcpy(com, token); printf("com = %s\n", com); token = strtok(NULL, " "); strcpy(file1, token); printf("file1 = %s\n", file1); token = strtok(NULL, " "); strcpy(file2, token); printf("file2 = %s\n", file2); }
When I run the program, I get a segmentation fault. Will this code run OK if there are no arguments, just a command? I'm sure the problem is with strtok() either way. thanks!



LinkBack URL
About LinkBacks




