【问题标题】:Using getopt for obtaining non-specified arguments C使用 getopt 获取非指定参数 C
【发布时间】:2013-11-14 21:03:51
【问题描述】:

我正在编写一个需要能够解析命令行参数的程序,我想使用 getopt。让它与常规参数一起使用没有问题,但是我需要它能够获取未使用标志指定的参数。例如,如果我运行:./prog -a a1 -b b2 foo 我需要能够获得 a1、a2 和 foo。现在它处理除了未指定的参数之外的所有内容。这是我所拥有的:

while((command = getopt(argc, argv, "a:b:c:")) != -1){
        switch(command){
            case('a'):
                input = fopen(optarg, "r");
                if(input == NULL){
                    printf("Error opening file, exiting\n");
                    exit( -1 );
                }
                break;

            case('b'):
                output = fopen(optarg, "r");
                if(output == NULL){
                    printf("Error opening file, exiting\n");
                    exit( -1 );
                }
                break;

            case('c'):
                keyword = optarg;
                break;


            case('?'):
                if((optopt == 'a') || (optopt == 'b') || (optopt == 'c')){
                    fprintf(stderr, "Error, no argument specified for -%c\n", optopt);
                    exit( -1 );
                } else
                    extra = optarg; // This is how I thought I needed to do it

                break;

            default:
                fprintf(stderr,"Error in getopt");
                break;
        }// switch
    } // while

谢谢!

【问题讨论】:

  • 我只是读到“一切正常,这是我的代码:[...]”你的问题是什么?
  • 它处理除未指定参数之外的所有内容。例如,如果用户输入一个没有标志 (a,b,c) 的参数,我的代码不会处理它。
  • 啊,好吧......那么你的OP是不利的。不过好的,明白了

标签: c command-line-arguments getopt


【解决方案1】:

循环之后,optind 变量将成为下一个非选项参数的索引。

例如也这样做

if (optind < argc)
{
    printf("Have extra arguments: ");
    for (int i = optind; i < argc; ++i)
        printf("%s ", argv[i]);
    printf("\n");
}

列出所有非选项参数。

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多