检查特定的命令行参数,然后将它们分配给变量

Check for specific command line arguments and then assign them to variables

这里是强制性的总菜鸟。

我正在制作一个简单的 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?)

非常感谢您的帮助。

我在 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-r-ilr 时,它会说:

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

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

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