使用getopt_long()函数的C语言

4

我一直在学习如何使用getopt_long(),以及如何使用optlong来“读取”多个字符选项。

我需要解析从终端输入的以下条目:

./bomb –n String –cp Integer –i Integer –c Integer –fc String

在使用getoptlong之前,我定义了我的短选项和长选项:

 if(argc != 11){
    perror("Error en numero de argumentos \n");
    exit(EXIT_FAILURE);
 }

 const char* const short_options = "n:i:c:";
 static struct option long_options[] = {
    {"cp", 1, NULL, 'a'},
    {"fc", 1, NULL, 'b'},
    {0, 0 , 0, 0}
 };

我的 short_options 捕获了一个带有参数的n(这就是冒号:的含义),ci同理。所以长选项也应该采用相同的方式(它们也都接受参数)。

    while(opt != -1){

        opt = getopt_long(argc, argv, short_options, long_options, NULL);

        switch (opt){   
           case 'n':
           //print it

           case 'a':
          //print it
         } 
    }

现在问题是,这段代码对于解析-c -i-n等参数可以完美工作,它进入所属的情况并正确打印输出。我的问题是,它对于-cp-fc无法正常工作。因为我以前没有使用过getopt(),所以我真的不知道怎么解决这个问题。
提前感谢。
1个回答

4
引用自man getopt_long

getopt_long()函数与getopt()函数类似,但它还接受以两个连字符开头的长选项。

并且

getopt_long_only()getopt_long()类似,但是---均可表示长选项。

所以您应该使用--cp--fc,或切换到getopt_long_only

getopt_long_only可以读取单字符选项(-n -i)和多字符选项(-cp -fc)吗? - Alessandroempire
2
@Alessandroempire 你自己有没有试着阅读手册? - melpomene
好的,我使用了getopt_long_only,因为它的行为类似于...。现在它进入了cp case,但没有进入fc case,这很奇怪。问题是:当我声明我的long_options时,当它遇到-fc时,它会返回b吗? - Alessandroempire

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接