getopt 总是返回 -1 / getopt 什么都不做

getopt always returning -1 / getopt not doing anything

我正在尝试使用 getopt() 解析命令行参数。下面是我的代码。 getopt() 总是返回 -1,无论我在 运行 程序时传递什么参数。

例如:

$ gcc -o test test.c
$ ./test f

有人能看出我做错了什么吗?谢谢你。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>

void usage (char * progname)
{
    fprintf(stderr, "Usage Instructions Here ...\n");
    exit(-1);
}


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

    while((opt = getopt(argc, argv, "?hf:")) != -1) {
        switch(opt) {
            case '?':
            case 'h':
                usage(argv[0]);
                break;
            case 'f':
                {
                    FILE *fp;
                    char *filename = strdup(optarg);

                    if((fp = fopen(filename, "r")) == NULL) {
                        usage(argv[0]);
                    } 
                }
                break;
            default:
                fprintf(stderr, "Error - No such opt, '%c'\n", opt);
                usage(argv[0]);
        }
    }

    return(0);
}

您实际上并没有在此处传递选项:

$ ./test f

选项应以 - 字符开头。 f 没有,所以它不被认为是一个选项。如果你这样称呼它:

$ ./test -f

你会得到这个:

./test: option requires an argument -- 'f'
Usage Instructions Here ...

此外,? 字符对 getopt 具有特殊含义。当发现未知选项时返回,并在 optopt 中存储无效选项的副本。所以您可能不想在选项字符串中使用 ?