计算C中字符串标记的数量

时间:2014-11-17 21:52:07

标签: c parameters terminal token strtok

我需要制作一个能够模拟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);

2 个答案:

答案 0 :(得分:0)

strtok()唯一能做的就是查找分隔符的下一个出现并用\0覆盖该字符并返回添加了偏移量的指针。指针保存在一个静态变量中,这就是为什么后来用char *的NULL调用它将在从找到最后一个分隔符的偏移量中使用的最后一个字符串上执行它。

这个页面有一个很好的例子: http://en.cppreference.com/w/c/string/byte/strtok

如果您只想计算参数,那么使用strchr()会更容易,此函数会搜索一个字符并返回指向其位置的指针。你可以像这样使用它。

unsigned int i = 0;
char *temp = token;
while ( (temp = strchr(temp, '') != NULL) ) {
    ++i;
}

这具有额外的好处,即在strtok()执行时不修改原始字符数组!

我会在你为每个命令创建的函数中处理这个问题。

您将所有选项传递给函数并在那里解析它。使用strtok()或您想要使用的任何其他内容。

这使得它在子程序中保持良好和干净,你将永远知道会发生什么。

if (strcmp("ls",token) == 0) {
    token = strtok(NULL," ");
    strcpy(path1,token);      // I would maybe change the path variable name to args
    ret = lscmd(path1);
    if (ret == -1) {
         // invalid input detected
    }  
}

然后你会有一个ls函数

int lsdcmd(char *args) {
    // parse args for argumants you are looking for, return -1 if it fails

    // do whatever you want to do.
}

答案 1 :(得分:0)

你可以用strtok这样计算参数:

示例:

const char* delimiter = ",";
char* tokens[MAX_NUM_OF_ARGS];

unsigned int index = 0;
char* temp = strtok(buff,delimiter);
while (temp!=NULL){
    if(index<MAX_NUM_OF_ARGS){
        tokens[index]=temp;
    }
    index++;
    temp = strtok(NULL,delimiter);
}

然后你可以遍历指针数组(标记)并比较它们......

相关问题