C - 用逗号分隔命令行参数

C - splitting command line arguments by commas

我知道在传递命令参数时,例如 a.out ls -l pwd cat hello.txt ,argv[0] 是 a.out,argv[1] 是 ls,argv[2] 是 -l等等等等

我想传递命令参数,以便它们用逗号而不是空格分隔 所以在命令 a.out ls -l, pwd, cat hello.txt 中:argv[1] 将是 ls -l,argv[2] 将是 pwd,argv[3] 将是 cat hello.txt

我当前的代码:

int main (int argc, char* argv[])
{
    int i;
    char str[100] = "";
    char* token;
    for (i = 1; i < argc; i++)
    {
        strcat(strcat(str, " "),argv[i]); // stores arguments in a string
        token = strtok (argv[i], ", "); // seperates arguments  by comma 
        printf("%s\n",token);
    }
    return 0;
}

它的输出:

ls
-a
pwd
cat
hello.txt

如果我做对了输出应该是:

ls -a
pwd
cat hello.txt

你的 token 变量只是一个字符数组,你需要一个双指针来存储每个参数的每个标记。 char [10][1000] buffer 之类的东西最多可以处理 10 个参数。

像这样的东西应该可以工作:

typedef struct{
    char rawCmd[9999];
    char *cmd;
    char *argv[9999];
} Command;

Command parsecommand(char *rawCommand, Command c){ 
    int i = 0;
    memset(c.rawCmd, 0, sizeof(c.rawCmd));
    strcat(c.rawCmd, rawCommand); // setting the whole thing to the structs rawCmd field just in case i need the whole thing
    char *ptr = strtok(rawCommand, " ");
    c.cmd = ptr; // gets the base cmd
    while (ptr != NULL)
    { // every element after the first will be an arg (if there are any!) 
        c.argv[i++] = ptr;
        ptr = strtok(NULL, " ");
    }
    c.argv[i++] = NULL;
    return c;
}
int main(int argc, char *argv[]){
    int i, iCommandCount = 0, iExitStatus = 0;  
    char cmd[6][9999], cur[9999]; 
    Command commands[6], c; 
    memset(&cur[0], 0, sizeof(cur));
    memset(&cmd[0], 0, sizeof(cmd));

    // seperates commands 
    for (i = 1; i < argc; i++){
        if (strcmp(argv[i], ",") != 0){
            strcat(cur, argv[i]);
            strcat(cur, " ");
        }
        if (strcmp(argv[i], ",") == 0 || i + 1 == argc){
            strcat(cmd[iCommandCount++], cur); 
            memset(&cur, 0, sizeof(cur));
        }
    }

    // splits commands by comma
    for (i = 0; i < iCommandCount; i++)
    {
        commands[i] = parsecommand(cmd[i], c);
        printf("commands: %s\n", commands[i].cmd);
    }

    return 0;
}

输出:

 a.out ls -l ,  pwd
commands: ls
commands: pwd
int main(int argc, char* argv[]) 
{
    int i;
    char str[100] = "";
    
    for (i = 1; i < argc; i++)
    {
        strcat(strcat(str, " "), argv[i]); // stores arguments in a string
        
        if (str[strlen(str)-1] == ',') {
            str[strlen(str)-1] = '[=10=]'; // remove comma at the end
            printf("%s\n", str);       // do something with your token
            str[0] = '[=10=]';             // reset str buf
        }
    }
    
    printf("%s\n", str); // do something with the remaining token

    return 0;
}

没有strtok的版本。

注意:如果您的参数列表不包含任何逗号,您将获得整个字符串列表(不以 'space' 分隔)。