3

我正在编写一个使用*argv[]参数的简单代码。我想知道我是否可以将getopt()函数用于以下意图。

./myprogram -a PATH
./myprogram PATH

该程序既可以仅采用PATH(例如/usr/tmp),也-a可以采用除PATH. 可以getopt()用于这种状态吗?如果可以,怎么做?

4

2 回答 2

4

该程序既可以仅采用PATH(例如/usr/tmp),也可以采用除PATH. 可以getopt()用于这种状态吗?如果可以,怎么做?

当然。我不确定你在哪里看到了潜在的问题,除非你不理解 POSIX 和getopt()'s 之间的区别optionsarguments。它们是相关的,但根本不是一回事。

getopt()在实际上没有指定选项的情况下很好,它使您可以访问非选项参数,例如PATH似乎适合您,无论指定了多少选项。通常的使用模型是循环调用getopt(),直到它返回-1以指示命令行中没有更多可用选项。在每一步,全局变量optindvariable 提供下一个argv要处理的元素的索引,并且 after getopt()(first) 返回 -1,optind提供第一个非选项参数的索引。在您的情况下,这将是您期望找到的地方PATH

int main(int argc, char *argv[]) {
    const char options[] = "a";
    _Bool have_a = 0;
    char *the_path;
    int opt;

    do {
        switch(opt = getopt(argc, argv, options)) {
            case -1:
                the_path = argv[optind];
                // NOTE: the_path will now be null if no path was specified,
                //       and you can recognize the presence of additional,
                //       unexpected arguments by comparing optind to argc
                break;
            case 'a':
                have_a = 1;
                break;
            case '?':
                // handle invalid option ...
                break;
            default:
                // should not happen ...
                assert(0);
                break;
        }
    } while (opt >= 0);
}
于 2019-03-07T14:02:16.660 回答
3

使用 optstring of"a"允许参数 of-a充当标志。
optind有助于检测仅存在一个附加参数。
该程序可以执行为./program -a path./program path

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

int main(int argc, char **argv)
{
    char op = ' ';//default value
    int opt;

    while ((opt = getopt(argc, argv, "a")) != -1)//optstring allows for -a argument
    {
        switch (opt)
        {
        case 'a':
            op = 'a';//found option, set op
            break;
        default:
            fprintf(stderr, "%s: unknown option %c\n", argv[0], optopt);
            return 1;
        }
    }
    if ( optind + 1 != argc)//one argument allowed besides optstring values
    {
        fprintf(stderr, "Usage: %s [-a] PATH\n", argv[0]);
        return 1;
    }

    printf("%s %c\n", argv[optind], op);
    return 0;
}
于 2019-03-07T14:03:10.787 回答