我正在制作一个自定义 C shell,并且当前使用空格分割命令:
(我当前正在做的事情的简化示例)
char *buf[20];
char *tempVar;
tempvar = strtok(buf, " ");
例如:
sleep 5
将分为 sleep
和 5
。
但是,我也想拆分 &
(以创建后台进程)。因此,sleep 5&
将分为 3 个:sleep
、5
和 &
。
任何帮助将不胜感激。
最佳答案
您可以使用特定的方法来提取数字,或者直接删除字符&
。我想到这里,也许这不是最好的解决方案。希望进一步交流。
char buf[] = "sleep 5&";
char *cmd;
char *arg;
char *tmpArg;
int count = 0;
while (true) {
if (0 == count) {
cmd = strtok(buf, " ");
arg = strtok(NULL, " ");
} else {
cmd = strtok(NULL, " ");
arg = strtok(NULL, " ");
}
printf("%s\n", cmd);
if (NULL != cmd) {
if (strcmp("sleep", cmd) == 0) {
if (arg != NULL) {
// 1. introduce a method to extract digit or
// 2. using `&` to split the arg again, the shortcoming is that we omit character `&` here.
for (int i = 0; i < 2; ++i) {
if (0 == i) {
tmpArg = strtok(arg, "&");
} else {
tmpArg = strtok(NULL, "&");
}
printf("%s\n", tmpArg);
}
}
}
} else {
break;
}
++count;
}
关于c - 使用 strtok 分割 c 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59313612/