View Single Post
  #1   (View Single Post)  
Old 14th March 2013
bsdplus bsdplus is offline
Real Name: Alan Cheng
Port Guard
 
Join Date: Jun 2009
Location: Shanghai, China
Posts: 21
Default Question on getopt and optind

Hello,


In getopt(3) man page, after arguments are processed in the while loop, there are two lines:

Code:
           argc -= optind;
           argv += optind;
Could somebody help explain the purpose of these two lines?

I played with the example code in getopt man page, "argc -= optind" seems to set argc to 0.
I also understand that "argv += optind" make the argv pointer pass over current argument string. But just could not figure out why we need to do that.

Thanks.

example code in getopt (3) man page:
Code:
           int bflag, ch, fd;

           bflag = 0;
           while ((ch = getopt(argc, argv, "bf:")) != -1) {
                   switch (ch) {
                   case 'b':
                           bflag = 1;
                           break;
                   case 'f':
                           if ((fd = open(optarg, O_RDONLY, 0)) == -1)
                                   err(1, "%s", optarg);
                           break;
                   default:
                           usage();
                           /* NOTREACHED */
                   }
           }
           argc -= optind;
           argv += optind;
Reply With Quote