简体   繁体   English

从命令行创建 arguments 并保存在数组中

[英]Create arguments from command line and save in an array

I'm trying to save my arguments and their parameters from the command line as follows我正在尝试从命令行保存我的 arguments 及其参数,如下所示

./run cat hello.txt: grep left: wc -c

I want to seperate each argument in an array as follows withouth knowing the number of :我想在不知道数量的情况下将数组中的每个参数分开如下:

char *cat_args[] = {"cat", "tests/nevermind", NULL};
char *grep_args[] = {"grep", "left", NULL};
char *cut_args[] = {"wc", "-c", NULL};

How can I achieve this?我怎样才能做到这一点?

int nbProc = 2;
for (int i = 0; i < argc; i++){
        if (strcmp(argv[i], ":") == 0){
            nbProc++;
        }
    }

int indice_debut[nbProc-2];
int j = 0;
for (int i = 1; i < argc; i++){
        if (strcmp(argv[i], ":") == 0){
            argv[i] = NULL;
            indice_debut[j] = i + 1;
            j++;
        }
    }

With this i'm able to get indice_debut = {4,7} because there is : in 4th and 7th position.有了这个,我可以得到indice_debut = {4,7}因为有:在第 4 和第 7 position。

I tried to run it as this but no luck, i'm doing this so i can use execvp .我试图这样运行它,但没有运气,我这样做是为了可以使用execvp

execvp(argv[indice_debut[0]], argv + indice_debut[0]);

Thanks谢谢

Allocate an array of pointers dynamically with malloc() .使用malloc()动态分配指针数组。 There can be at most argc/2 commands, since the worst case is alternating word: word: word: ... , so allocate that many elements.最多可以有argc/2命令,因为最坏的情况是交替word: word: word: ... ,所以分配那么多元素。 The array elements can point to the elements of argv , and you can replace the : argument with a null pointer to end each subcommand.数组元素可以指向argv的元素,您可以将:参数替换为 null 指针以结束每个子命令。

int main(int argc, char **argv) {
    if (argc < 2) {
        printf("At least one command is required\n");
        exit(1);
    }

    char **arg_arrays = malloc(argc/2 * sizeof *arg_arrays);
    int array_index = 0;
    int arg_index = 0;
    while (arg_index < argc) {
        arg_arrays[array_index++] = &argv[arg_index];
        for (; arg_index < argc && strcmp(argv[arg_index], ":") != 0; arg_index++) {}
        argv[arg_index] = NULL;
    }

    // Execute each of the subcommands
    for (int i = 0; i < array_index; i++) {
        pid_t pid = fork();
        if (pid == 0) {
            execvp(arg_arrays[i][0], arg_arrays[i]);
        } else if (pid < 0) {
            perror("fork");
            exit(1);
        }
    }
    // wait for all the subcommands to finish
    while (wait(NULL) > 0) {}
}

This is just a simple example of how to parse the subcommands and execute them.这只是一个如何解析子命令并执行它们的简单示例。 If you want to pipe from one command to the next one you'll need to add that code.如果您想将 pipe 从一个命令转移到下一个命令,则需要添加该代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM