【问题标题】:Getopt() Error CheckingGetopt() 错误检查
【发布时间】:2017-12-06 02:28:11
【问题描述】:

我正在尝试使 getopt 可以处理某些标志,但是我在使用 getopt 实现错误处理时遇到了麻烦。我想防止重复的标志,例如'-s 1 -s 1',并且标志'-s 1 2'的参数过多,这两者都应该退出程序。

 int opt; //command flags
 while((opt = getopt(argc, argv, "s:f:")) != -1){
 switch(opt){
  case 's':
    printf("%s\n", optarg);
    printf("%i\n", optind);
    break;
  case 'f':
    printf("%s\n", optarg);
    printf("%i\n", optind);
    break;
  default:
    //unknown command flags
    fprintf(stderr, "Usage:  fred [ -s symbol-table-file ] [ -f fred-program-file ]\n");
    return EXIT_FAILURE;
  }
}

参数过多(例如,程序 -s f1 -f f2 hello)。重复的标志(例如,程序 -s f1 -s f2)。两者都应该退出程序

【问题讨论】:

  • 额外的参数必须在循环后检测;它将显示为“未使用”参数,optind < argc 将在循环退出时保持不变。重复的参数在循环之前需要int sflag = 0;,在case 's': 代码中需要if (sflag++ > 0) { …chastise user and exit… }

标签: c error-handling getopt


【解决方案1】:

对于每个选项,您可以维护一个标志以查看该选项是否已经遇到过。在这些标志的帮助下检测到重复的选项。

int c, sflag=0, fflag=0;
while( (c=getopt(argc, argv, "s:f:"))!=-1 )
{
    switch(c)
    {
    case 's':
        if(sflag!=0)
        {
            //fprintf(stderr, "\n dup s option");
            return 1; //duplicate s option
        }   
        sflag++;
        //printf("\ns flag: %s", optarg);
        break;
    case 'f':
        if(fflag!=0)
        {
            //fprintf(stderr, "\n dup f option");
            return 1; //duplicate f option
        }   
        fflag++;
        //printf("\nf flag: %s", optarg);
        break;
    case '?':
        if(isprint(optopt))
        {
            fprintf(stderr, "Unknown option %c", optopt);
        }
        else
        {
            fprintf(stderr, "\nUnknown option character x%x", optopt);
        }
        return 1;
    }
}   

optind 将具有下一个argv[] 的索引,该索引仍有待检查。在处理完所有选项之后,在您的程序中应该只有一个非选项参数。

因此,optind 必须等于 argc-1 才能正确使用该命令。

if(optind != argc-1) //exactly one non-option argument is expected
{
    fprintf(stderr, "\nInvalid number of arguments.");
    return 1;
}

【讨论】:

    猜你喜欢
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2014-06-08
    相关资源
    最近更新 更多