开发者

getopt giving -1 as return value

开发者 https://www.devze.com 2023-04-11 19:08 出处:网络
I am trying to see how getopts work. I wrote the code below but not sure what I am doing wrong. Please point me :

I am trying to see how getopts work. I wrote the code below but not sure what I am doing wrong. Please point me :

#include<unistd.h>
.. 
..
int main( int argc, char *argv[])
{
  int ch=0;
   while((ch=getopt(argc, argv, "ltR:")!=-1) // 0 here was by mistake. Changed to -1
    {  
      printf("%d",ch); //This prints -1 
       switch(ch)
               {
                 case 'l':
                 printf("l");
                 break;
                 case 't':
                 printf("t");
      开发者_Go百科           break;
                 case 'R':
                 printf("R");
                 break;
                }
    }
   return 0;
 }

 $ ./a.out -ltR 
 $ -1
 $ ./a.out -l 
 $ -1

May be I am doing a really mistake or missing out on some aspect of my understanding of getopt.

Made changes but still gives the same result:(

Thanks, Faizan


I think your while expression should be

while((ch=getopt(argc, argv, "ltR")!=-1)
{..}

and the option should end with ':'

while((ch=getopt(argc, argv, "ltR:")!=-1)
{..}

or two ':' if switch is optional.


From the man page -1 indicates that all the arguments have been done, rather than 0 as you appear to be checking for.

man 3 getopt

If an option was successfully found, then getopt() returns the option character. If all command-line options have been parsed, then getopt() returns -1.

The code in your question doesn't parse out of the box so it doesn't appear to be a proper copy paste which makes spotting the error a lot harder. The brackets on the while loop might be the cause of your issue but it's hard to tell. If I copy paste your example and correct the bracket issue the code works as you expect it to.

0

精彩评论

暂无评论...
验证码 换一张
取 消