首页 > 解决方案 > 检查特定的命令行参数,然后将它们分配给变量

问题描述

强制性的总菜鸟在这里。

我正在制作一个简单的 C 程序,它从一个简单函数的文件中读取一些变量。然而,我想要完成的是允许调用程序的人覆盖从文件中读取的值,如果他们在命令行参数中指定的话。我想要这样的东西:

char* filename;
int number;
...
readConfig(filename, number, ...);
if (argc > 1) {
    // Check if the variables were in the args here, in some way
    strcpy(filename, args[??]);
    number = atoi(args[??]);
}

我希望程序被称为

program -filename="path/to/file.txt" -number=3

我发现我可以标记每个参数并将其与每个可分配变量匹配并丢弃其他变量,但我很确定有一种更优雅的方法可以做到这一点(也许使用 getopts?)

非常感谢你的帮助。

标签: clinuxcommand-line-arguments

解决方案


我在geeksforgeeks上找到了这个:

#include <stdio.h>
#include <unistd.h>

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

    // put ':' in the starting of the
    // string so that program can
    //distinguish between '?' and ':'
    while((opt = getopt(argc, argv, ":if:lrx")) != -1)
    {
        switch(opt)
        {
            case 'i':
            case 'l':
            case 'r':
                printf("option: %c\n", opt);
                break;
            case 'f':
                printf("filename: %s\n", optarg);
                break;
            case ':':
                printf("option needs a value\n");
                break;
            case '?':
                printf("unknown option: %c\n", optopt);
                break;
        }
    }
    // optind is for the extra arguments
    // which are not parsed
    for(; optind < argc; optind++){
        printf("extra arguments: %s\n", argv[optind]);
    }

    return 0;
}

所以,当你通过时-f,你还需要传递文件名,比如:./args -f filename它会说:

$ ./a.out -f file.txt
filename: file.txt

当你通过-i, -l, or -r, or-ilr时,它会说:

$ ./a.out -ilr
option: i
option: l
option: r

如果你通过-f但没有文件名,它会说选项需要参数。其他任何内容都将打印到额外的参数

因此,有了它,您可以向 getopts 添加选项、添加新案例、做一件事,例如: getopts(argc, argv, ":fn:") -f 文件名、-n 编号,非常简单


推荐阅读