我想在我的 C(仅 C)程序中解析用户输入命令。示例命令:
add node ID
add arc ID from ID to ID
print
exit
等等。然后我想对 ID 进行一些验证并将它们转发到指定的函数。功能和验证当然已经准备好了。这都是关于解析和匹配函数......
我已经用许多 if
和 strtok
实现了它,但我确信这不是最好的方法......有什么想法(库)吗?
最佳答案
我认为你想要的是这样的:
while (1)
{
char *line = malloc(128); // we need to be able to increase the pointer
char *origLine = line;
fgets(line, 128, stdin);
char command[20];
sscanf(line, "%20s ", command);
line = strchr(line, ' ');
printf("The Command is: %s\n", command);
unsigned argumentsCount = 0;
char **arguments = malloc(sizeof(char *));
while (1)
{
char arg[20];
if (line && (sscanf(++line, "%20s", arg) == 1))
{
arguments[argumentsCount] = malloc(sizeof(char) * 20);
strncpy(arguments[argumentsCount], arg, 20);
argumentsCount++;
arguments = realloc(arguments, sizeof(char *) * argumentsCount + 1);
line = strchr(line, ' ');
}
else {
break;
}
}
for (int i = 0; i < argumentsCount; i++) {
printf("Argument %i is: %s\n", i, arguments[i]);
}
for (int i = 0; i < argumentsCount; i++) {
free(arguments[i]);
}
free(arguments);
free(origLine);
}
在释放所有内容之前,您可以使用“命令”和“参数”执行您想要的操作。
关于c - 在 C 中像 shell 一样解析命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112038/