C - 解析带有未知数量参数的命令行

标签 c parsing command-line

<分区>

Possible Duplicate:
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

关于如何将其放入代码中有什么建议吗?

最佳答案

这就是 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;

关于C - 解析带有未知数量参数的命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3848215/

相关文章:

linux - 使用配置文件的 bash 命令的别名

c - 尝试访问结构数组成员时出现段错误

c - 为什么String从Scheme传递给C时不是String?

c++ - 仅适用于 .NET 的 Windows API W7 JumpList?

parsing - Powershell中的文本解析: Identify a target line and parse the next X lines to create objects

xml - 在 R 中,如何从 XML 文件中提取两个值,遍历 5603 个文件并写入表

java - 使用 Java 在远程计算机上运行命令行

c - 在 C 中的结构内初始化 char* 值

c# - 我永远无法预测 XMLReader 的行为。有什么理解技巧吗?

windows - 批处理文件 : How to capture output of a function in a variable?