首页 > 解决方案 > c语言中getopt函数的困惑

问题描述

我编写了一个带有 getopt 函数的代码,如下所示:

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

int main(int argc, char *argv[]){
    int result;
    opterr=0;
    puts("The following parsed outcome to command-line argments by getopt(-a, -b* or -c*):");
    while((result=getopt(argc, argv, "ab:c::"))!=-1){
        switch(result){
        case ':':
            printf("getopt returns \'%c\'\toptopt=%c\toptarg=%s\toptind=%d\t", result, optopt, optarg, optind);
            break;
        case '?':
            if(optopt=='b')
                fprintf(stderr, "Option -%c requires an argument attached. optarg=%s\toptind=%d\t", optopt, optarg, optind);
            else if(isprint(optopt))
                fprintf(stderr, "Unknown option \'%c\'.\toptarg=%s\toptind=%d\t", optopt, optarg, optind);
            else
                fprintf(stderr, "Unknown option character \'%x\'.\toptarg=%s\toptind=%d\t", optopt, optarg, optind);
            break;
        default:
            printf("getopt returns \'%c\'\toptarg=%s\toptind=%d\t", result, optarg, optind);
            break;
        }
        printf("argv[%d]=%s\n", optind, argv[optind]);}

    puts("Here is parsed argument values:");
    for(result=1; result<argc; result++)
        printf("argv[%d]=%s\n", result, argv[result]);
    for(; optind<argc; optind++)
        printf("No-option argument values: argv[%d]=%s\n", optind, argv[optind]);
    return 0;
}

然后我将上面的程序编译成名为parse. 使用以下命令行参数运行解析:

./parse -ac b

这是输出:

  The following parsed outcome to command-line argments by getopt:
  getopt returns 'a'      optarg=(null)   optind=1        argv[1]=-ac
  getopt returns 'c'      optarg=(null)   optind=2        argv[2]=b
  Here is parsed argument values:
  argv[1]=-ac
  argv[2]=b
  No-option argument values: argv[2]=b

getopt我的困惑是为什么在c遇到. 因为它不是。在我的期望中,假设执行语句cargv[1] ac-ccase '?':

标签: clinuxparsingcommand-line

解决方案


使用 时getopt,可以将不带参数的单字符选项与以下选项结合使用。这就是使打字成为可能的原因

ls -lR

即使以下选项带有参数,这也有效。


推荐阅读