2

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?

Community
  • 1
  • 1
Anon
  • 127
  • 1
  • 3
  • 11
  • 2
    This seems to be the same as [ Parse string into argv/argc ](http://stackoverflow.com/questions/1706551/). In particular, see the [GLib answer](http://stackoverflow.com/questions/1706551/parse-string-into-argv-argc/1706610#1706610). – Matthew Flaschen Oct 03 '10 at 02:00

1 Answers1

0

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
  • 233,326
  • 40
  • 323
  • 462