getopt的可选参数? [英] Getopt optional arguments?

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

问题描述

我有,你输入一个选项程序
    -d
然后你是否不是选项后提供一个非可选参数,做一些事情。我的继承人code:

I have a program where you enter an option -d and then whether or not you supply a non-optional argument after the option, do something. Heres my code:

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

#define OPT_LIST "d::" 

int main (int argc, char *argv[])
{
    int c;
        char string[] = "blah";

    while ((c = getopt (argc, argv, OPT_LIST)) != -1)
    {
        switch (c)
        {
            case 'd':
                    printf("%s\n", optarg);
                    break;

            case '?':
                fprintf(stderr, "invalid option\n");
                exit(EXIT_FAILURE);
        }   
    }
}

所以,如果你的选项之后输入非可选参数,它打印的说法。但我想它打印出的字符串,如果用户不提供非可选参数(这就是为什么我把双冒号在
    OPT_LIST)。但我不知道如何做到这一点,因此任何帮助将不胜AP preciated。

So if you enter a non-optional argument after the option, it prints the argument. But I want it to print out the char "string" if the user doesn't supply a non-optional argument (this is why I put the double colon in the OPT_LIST). But I'm not sure how to do this so any help would be greatly appreciated.

下面有什么,当我运行的程序发生了:

Heres what happens when I run the program:

user:desktop shaun$ ./arg -d hello
hello
user:desktop shaun$ ./arg -d 
./arg: option requires an argument -- d
invalid option

我用C语言编写运行在Mac的OS X。

I'm running a Mac with OS X using C language.

推荐答案

在选项可选值功能仅仅是一个GNU libc的延伸,而不是由POSIX必需的,可能是简单地通过附带的Mac OS libc中得到执行[X]。

The "optional value of an option" feature is only a GNU libc extension, not required by POSIX, and is probably simply unimplemented by the libc shipped with Mac OS X.

选项的说法是指定适用于此程序的选项字符的字符串。此字符串中的选项字符可以跟一个冒号(':')来表示,它需要一个必需的参数。如果一个选项字符后跟两个冒号(::),它的参数是可选的;这是一个GNU扩展。

The options argument is a string that specifies the option characters that are valid for this program. An option character in this string can be followed by a colon (‘:’) to indicate that it takes a required argument. If an option character is followed by two colons (‘::’), its argument is optional; this is a GNU extension.

<一个href=\"https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html\">https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html

事实上,POSIX.1-2008,第12.2节,实用程序语法准则,明确禁止该功能:

In fact, POSIX.1-2008, section 12.2, "Utility Syntax Guidelines", explicitly forbids this feature:

准则7:选项参数不宜选用

Guideline 7: Option-arguments should not be optional.

<一个href=\"http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02\">http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02

这篇关于getopt的可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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