I’m writing a program for a school project that is supposed to emulate the Unix shell, in a very basic form. It’s basically parsing input, then doing a fork/exec. I need to be able to read arguments in the program (not as arguments passed to the program from the command line) individually. For example, I will prompt:
Please enter a command:
…and I need to be able to parse both…
ls
OR
ls -l
but the trouble is that there seems to be no easy way to do this. scanf() will pull each argument individually, but I see no way to place them into differing slots in a char* array. For example, if I do…
char * user_input[10];
for (int i=0; i<10; i++){
user_input[i] = (char *) malloc(100*sizeof(char));
}
for (int i=0; *(user_input[i]) != '@'; i++)
{
scanf("%s", user_input[index]);
index++;
}
…then user_input[0] will get "ls", then the loop will start over, then user_input[0] will get "-l".
gets and fgets just take the whole line. Obviously this problem can be logically solved by going through and plucking out each individual argument…but I’d like to avoid having to do that if there is an easy way that I’m missing. Is there?
Thanks!
If your use case is simple enough, you can do this with strtok:
You can use
strtokorstrtok_rto split the string on spaces.If you’re doing something more complex, where some of the arguments could have (quoted) spaces in them, you’re pretty much stuck parsing it yourself – though you could have a look at the source of a shell (e.g. bash) to see how it handles it.
kilanash helpfully reminds me of my obvious omission – GNU getopt. You’ll still have to have parsed into separate arguments yourself first, though.