【发布时间】:2014-11-17 21:52:06
【问题描述】:
我需要制作一个模拟 Linux 终端的程序。由于某些系统调用需要 1,2 个或更多参数,因此我想确保给定的参数数量是正确的。我使用strtok() 将调用名称与参数分开,但我需要知道strtok() 创建了多少个标记来比较它。
下面是示例代码:
char *comand = (char*) malloc(sizeof(char)*100);
char *token;
char *path1 = (char*) malloc(sizeof(char)*100);
char *path2= (char*) malloc(sizeof(char)*100);
fgets(comand, 100, stdin);
printf( "\nYou entered: %s \n", comand);
token = strtok(comand ," ");
//Check the number of tokens and add a condition in each IF to match
if (strcmp("ls",token) == 0) {
token = strtok(NULL," ");
strcpy(path1,token);
}
else if (strcmp("cat",token) == 0) {
token = strtok(NULL," ");
strcpy(path1,token);
}
else if (strcmp("cp",token) == 0) {
token = strtok(NULL," ");
strcpy(path1,token);
token = strtok(NULL," ");
strcpy(path2,token);
}
else if (strcmp("mv",token) == 0) {
token = strtok(NULL," ");
strcpy(path1,token);
token = strtok(NULL," ");
strcpy(path2,token);
}
else if (strcmp("find",token) == 0) {
token = strtok(NULL," ");
strcpy(path1,token);
}
else if (strcmp("rm",token) == 0) {
token = strtok(NULL," ");
strcpy(path1,token);
}
else if (strcmp("mkdir",token) == 0) {
token = strtok(NULL," ");
strcpy(path1,token);
}
else if (strcmp("rmdir",token) == 0) {
token = strtok(NULL," ");
strcpy(path1,token);
}
else if (strcmp("quit",token) == 0) {
exit(0);
}
else print("Number of parameters do not match);
【问题讨论】:
-
“系统调用”?从控制台?
-
不,这个“终端”的“系统调用”是用 C 语言编写的程序,而不是 Unix 程序。如果命令是“ls”,那么我会调用一个名为“commLs”或类似名称的过程,并将令牌传递给它。
-
您可能还想检查这个问题:stackoverflow.com/questions/13078926/…
-
引号怎么办?
标签: c parameters terminal token strtok