getopt用法(带/不带选项) [英] getopt usage with/without option

查看:74
本文介绍了getopt用法(带/不带选项)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a simple code making use of *argv[] parameter. I'd like to know whether I can use getopt() function for the following intent.

./myprogram -a PATH
./myprogram PATH

该程序可以仅采用PATH(例如/usr/tmp),也可以采用-a选项. getopt()可以用于此状态吗?如果可以,怎么办?

The program can either take merely PATH (e.g. /usr/tmp) or take -a option in addition to PATH. Can getopt() be used for this state? If can, how?

推荐答案

该程序可以仅采用PATH(例如/usr/tmp),也可以采用除PATH之外的其他选项. getopt()可以用于此状态吗?如果可以,怎么办?

The program can either take merely PATH (e.g. /usr/tmp) or take option in addition to PATH. Can getopt() be used for this state? If can, how?

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

Certainly. I'm not sure where you even see a potential issue, unless its that you don't appreciate POSIX's and getopt()'s distinction between options and arguments. They are related, but not at all the same thing.

getopt()可以在不指定任何选项的情况下很好地使用,它使您可以访问非选项参数,例如PATH似乎适合您,而无论指定了多少选项.通常的用法模型是循环调用getopt(),直到返回-1为止,以指示命令行中没有更多选项可用.在每个步骤中,全局变量optind变量提供下一个要处理的argv元素的索引,在getopt()(第一个)返回-1之后,optind提供第一个非选项参数的索引.就您而言,这就是您希望找到PATH的地方.

getopt() is fine with the case that no options are in fact specified, and it gives you access to the non-option arguments, such as PATH appears to be for you, regardless of how many options are specified. The usual usage model is to call getopt() in a loop until it returns -1 to indicate that no more options are available from the command line. At each step, the global variable optind variable provides the index of the next argv element to process, and after getopt() (first) returns -1, optind provides the index of the first non-option argument. In your case, that would be where you expect to find 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);
}

这篇关于getopt用法(带/不带选项)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆