getopt()原型

int getopt( int argc, char *const argv[], const char *optstring );

给定了命令参数的数量 (argc)、指向这些参数的数组 (argv) 和选项字符串 (optstring) 后,getopt() 将返回第一个选项,并设置一些全局变量。使用相同的参数再次调用该函数时,它将返回下一个选项,并设置相应的全局变量。如果不再有识别到的选项,将返回 -1,此任务就完成了。

getopt() 所设置的全局变量包括:

  • optarg——指向当前选项参数(如果有)的指针。
  • optind——再次调用 getopt() 时的下一个 argv 指针的索引。
  • optopt——最后一个已知选项。

对于每个选项,选项字符串 (optstring) 中都包含一个对应的字符。具有参数的选项(如示例中的 -l-o 选项)后面跟有一个 : 字符。示例所使用的 optstringIl:o:vh?(前面提到,还要支持最后两个用于打印程序的使用方法消息的选项)。

可以重复调用 getopt(),直到其返回 -1 为止;任何剩下的命令行参数通常视为文件名或程序相应的其他内容。

/* doc2html supports the following command-line arguments:
*
* -I - don't produce a keyword index
* -l lang - produce output in the specified language, lang
* -o outfile - write output to outfile instead of stdout
* -v - be verbose; more -v means more diagnostics
* additional file names are used as input files
*
* The optString global tells getopt() which options we
* support, and which options have arguments.
*/
struct globalArgs_t {
       int noIndex;                            /* -I option */
       char *langCode;                         /* -l option */
       const char *outFileName;        /* -o option */
       FILE *outFile;
       int verbosity;                          /* -v option */
       char **inputFiles;                      /* input files */
       int numInputFiles;                      /* # of input files */
} globalArgs;
static const char *optString = "Il:o:vh?";

opt = getopt( argc, argv, optString );
    while( opt != -1 ) {
        switch( opt ) {
            case 'I':
                globalArgs.noIndex = 1; /* true */
                break;
                
            case 'l':
                globalArgs.langCode = optarg;
                break;
                
            case 'o':
                globalArgs.outFileName = optarg;
                break;
                
            case 'v':
                globalArgs.verbosity++;
                break;
                
            case 'h':   /* fall-through is intentional */
            case '?':
                display_usage();
                break;
                
            default:
                /* You won't actually get here. */
                break;
        }
        
        opt = getopt( argc, argv, optString );
    }
    globalArgs.inputFiles = argv + optind;

globalArgs.numInputFiles = argc - optind;

convert_document();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值