views:

76

answers:

1

Possible Duplicate:
Parse string into argv/argc

I'm trying to write a fake shell using C, so I need to be able to take a command and then x number of arguments for the command. When I actually run the command, I'm just using execvp(), so I just need to parse the arguments into an array. But I wasn't really sure how to do this without knowing the exact number. I was thinking something in pseudo code like:

while (current char in command line != '\n')
     if current char is a space, increment a counter
parse characters in command line until first space and save into a command variable
for number of spaces
     while next char in command line != a space
          parse chars into a string in an array of all of the arguments

Any suggestions on how to put this into code?

A: 

This is the kind of thing that strtok() is designed for:

#define CMDMAX 100

char cmdline[] = "  foo bar  baz  ";
char *cmd[CMDMAX + 1] = { 0 };
int n_cmds = 0;
char *nextcmd;

for (nextcmd = strtok(cmdline, " "); n_cmds < CMDMAX && nextcmd; nextcmd = strtok(NULL, " "))
    cmd[n_cmds++] = nextcmd;
caf