【问题标题】:Parsing Multiple Argument Line解析多个参数行
【发布时间】:2016-07-29 13:44:28
【问题描述】:

我实际上遇到了麻烦,我想解析多个参数行:

./a.out -a 0 L
./a.out -ab
./a.out -abc

我尝试使用 getopt 来实现,但没有成功。事实是我无法处理多个参数,例如

./a.out -abc
./a.out -edg

有没有什么方法可以按照我想要的方式使用 getopt 之类的函数?

或者我应该考虑这样做(使用 getopt):

./a.out -a -b
./a.out -a -b -c

【问题讨论】:

  • 您在尝试使用 getopt 时遇到了什么问题?
  • 问题是:“./a.out -a 0 J”是我的程序的第一个选项,它有两个参数。 "./a.out -abc" 是另一个选项,它不接受除“-”之后的参数之外的任何其他内容。所以我的问题是我实际上不能将它们结合起来来解析我的命令行。
  • 为什么需要 2 个参数?为什么不使用不同的语法?即:“./a -a 0,J -abc”
  • 关于参数:“./a.out -a 0”用于读取我的数据库中的特定条目(给出参数,它将返回 0 条目)。当 "./a.out -ab" 返回数据库中的所有条目时
  • 那么“J”是什么意思?

标签: c parsing command-line-arguments getopt


【解决方案1】:

"a::" 使 -a 带有可选参数。 -a 本身设置options 标志以获取两个单独的参数。 -aopt 附加选项接受opt

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

int main(int argc, char *argv[])
{
    int c = 0;
    int each = 0;
    int options = 0;

    if ( !( argc == 2 || argc == 4)) {
        fprintf(stderr, "Usage:\t%s -aopt\n or\n\t%s -a opt1 opt2\n", argv[0], argv[0]);
        return 1;
    }
    while((c = getopt(argc, argv, "a::")) != -1) {

        switch(c) {
            case 'a':
                if ( optarg) {// -aopt
                    printf ( "%s\n", optarg);
                }
                else {
                    options = 1;// -a by itself
                }
                break;
            default:
                fprintf(stderr, "Usage:\t%s -aopt\n or\n\t%s -a opt1 opt2\n", argv[0], argv[0]);
                return 1;
        }
    }
    if ( optind + 2 == argc) {
        if ( options) {
            for ( each = optind; each < argc; each++) {
                if ( ( argv[each][0] != '-')) {
                    printf ( "found argument %s\n", argv[each]);
                }
            }
        }
        else {
            fprintf(stderr, "Usage:\t%s -aopt\n or\n\t%s -a opt1 opt2\n", argv[0], argv[0]);
            return 1;
        }
    }

    return 0;
}

【讨论】:

  • 这正是我要找的东西,非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 2019-07-10
  • 1970-01-01
  • 2020-08-19
  • 2011-02-02
  • 1970-01-01
  • 2013-03-06
相关资源
最近更新 更多