C - 使用未知数量的参数解析命令行

时间:2010-10-03 01:49:26

标签: c parsing command-line

  

可能重复:
  Parse string into argv/argc

我正在尝试使用C编写一个假shell,所以我需要能够为命令执行命令然后x个参数。当我实际运行命令时,我只是使用execvp(),所以我只需要将参数解析为数组。但我不确定如何在不知道具体数字的情况下做到这一点。我正在用伪代码思考:

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

有关如何将其放入代码的任何建议吗?

1 个答案:

答案 0 :(得分:0)

这是strtok()的设计目标:

#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;
相关问题