c - getopt 总是返回 -1/getopt 不执行任何操作

标签 c unix getopt

我正在尝试使用 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 中存储无效选项的副本。因此,您可能不想在选项字符串中使用 ?

关于c - getopt 总是返回 -1/getopt 不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47315677/

相关文章:

c - 如何获取系统(program.exe)的输入?

c - 像tcl的vwait,C编程有没有?

日历时间存储为带符号的 32 位整数 - 何时溢出

python - 使所有新目录具有 777 权限

bash - 捕获 getopt 无效选项

c - 如何知道 C 程序是否支持选项

c - strcmp() 的段错误

c - 如何用 C 语言创建一个程序,编译并运行另一个 C 程序并将输出保存在 txt 文件中?

linux - Bash - if 语句不会自动运行

c - C语言中的optopt和getopt