在C中解析命令行输入

时间:2016-11-17 17:16:18

标签: c parsing token

所以我必须创建一个像shell和文件系统这样的unix。我目前坚持让程序接受命令,如ls,cd,stat,exit。每当输入“ls”时,它只会再次返回printf行。但是,如果你做“ls l”,它打印出“你输入了ls”,这或多或少是我想要的,但是在ls之后我不需要任何东西。对于我上面列出的命令,我只想输入命令,不需要输入其他空格或字符。但是,如果我使用“cd”,我希望程序能够区分在命令之后需要输入某个目的地的事实,我相信这是正常的。有人能告诉我哪里出错了吗?

int main(int argc, char *argv[]){

char cmd[50];
const char spc[50] = " ";
char *file, *dir;
char *tok, *nextName;


while(1){
    printf("Russ_John_Shell> ");
    fgets(cmd, 50, stdin);

    //Tokenizes string to determine what command was inputed as well as any file/directory name needed
    tok = strtok(cmd, spc);
    nextName = strtok(tok, spc);


    //Checks to see whether the string has a file/directory name after the command
    if (strcmp(cmd, tok) == 0){
        if (strcmp(cmd, "ls") == 0){
            listDir(cmd);
        } else if (strcmp(cmd, "stat") == 0){
            status(cmd);
        } else if (strcmp(cmd, "exit") == 0){
            exitShell(cmd);
        }
    } else {
        if (strcmp(cmd, "cd") == 0){
            changeDir(cmd);
        } else if (strcmp(cmd, "mkdir") == 0){
            makeDir(cmd);
        } else if (strcmp(cmd, "mkfs") == 0){
            makeFS(cmd);
        } else if (strcmp(cmd, "rmdir") == 0){
            remDir(cmd);
        } else if (strcmp(cmd, "mkfile") == 0){
            makeFile(cmd);
        } else if (strcmp(cmd, "rmfile") == 0){
            remFile(cmd);
        } else {
            printf("Command %s not recognized.\n", "cmd");
        }
    }
}
}

0 个答案:

没有答案