小编pud*_*ter的帖子

Getopt可选参数?

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

#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);
        }   
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果在选项后输入非可选参数,则会打印参数.但是如果用户没有提供非可选参数,我希望它打印出char"string"(这就是为什么我把双冒号放在OPT_LIST中).但我不知道如何做到这一点,所以任何帮助将不胜感激.

下面是我运行程序时会发生什么:

user:desktop shaun$ ./arg -d hello
hello
user:desktop shaun$ ./arg -d 
./arg: option requires an argument -- d
invalid option
Run Code Online (Sandbox Code Playgroud)

我正在使用C语言运行带有OS X的Mac.

c arguments getopt optional option

8
推荐指数
2
解决办法
3万
查看次数

标签 统计

arguments ×1

c ×1

getopt ×1

option ×1

optional ×1