c - 将字符数组解析为 ***char

标签 c arrays shell parsing char

由于 gets() (这是输入到我的 shell 的命令),我得到了一个字符数组,例如“ls -l\| sort”。现在我想要一个 char*** 来保存指向特定命令的指针(因此用 | 分隔)。以我的例子:

*1[] = {"ls", "-l", "\", null}
*2[] = {"sort", null}

我的角色***将是{1,2}。问题是,我不知道在这个字符数组中将给我多少个字符串,所以我无法预定义它。我现在所拥有的只是通过空格将字符数组分割成单词,我不知道如何做我真正需要的事情。

此外,在上面的输入/输出中,函数应该对“ls -l\|sort”和“ls -l\| sort”做出相同的 react

到目前为止我的代码:

int parse(char *line, char **argv)
{
    while (*line != '\0') {     
        while (*line == ' ' || *line == '\t' || *line == '\n')
            *line++ = '\0'; 
        *argv++ = line;     
        while (*line != '\0' && *line != ' ' && *line != '\t' && *line != '\n'){
            line++;
        }
    }
    *argv = '\0';  
    return 0; 
}

最佳答案

要分割一行,请使用strtok()。您可以使用此函数,将 | 作为分隔符,然后使用 :

#include <string.h>

int parse(char *line, char **argv, const char *delim)
{
    int word_counter = 0
    /* get the first word */
    char *word = strtok(line, delim);

    /* walk through other words */
    while (word != NULL) 
    {
       printf(" %s\n", word);
       word_counter++; 

       /* save word somewhere */

       word = strtok(NULL, delim);
    }

    printf("This string contains %d words separated with %s\n",word_counter,delim);
}

关于c - 将字符数组解析为 ***char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27090646/

相关文章:

将 void* 转换为 long*

c# - 如何使用列开始初始化 "List of list"

arrays - 使用 set -u 从 bash 中的关联数组中获取元素

php - 将平面数组拆分为包含输入数组中连续键值的分组子数组

shell - 使用awk输出csv2md格式

Python C API : PyEval_CallFunction?

c - 给定两个绝对路径,如何找到相对路径?

c - 使用 scanf() 读取整数以在 for 循环中使用

linux - 我可以在没有 cron 或 incron 的 Linux 服务器上连续运行 inotifywait

bash - 如何传递 "one"参数并在 "xargs"命令中使用它两次