What do these codes do?

I saw this source code in a book:

#include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { char *delivery = ""; int thick = 0; int count = 0; char ch; while ((ch = getopt(argc, argv, "d: t")) != EOF) switch(ch) { case 'd': delivery = optarg; break; case 't': thick = 1; break; default: fprintf(stderr, "Unknown option: '%s'\n", optarg); return 1; } argc -= optind; argv += optind; if (thick) puts("Thick Crust."); if (delivery[0]) printf("To be deliverd %s\n", delivery); puts("Ingredients: "); for (count = 0; count < argc; count++) puts(argv[count]); return 0; } 

I can understand the whole source except:

 argc -= optind; argv += optind; 

I know what argc and argv are, but what happens on these two lines, what is optind, Explain to me.

Thanks.

+4
source share
4 answers

The getopt library provides several functions to help analyze command line arguments.

When you call getopt , it "eats" a variable number of arguments (depending on the type of command line option); the number of arguments "eaten" is indicated in the optind global variable.

Your code configures argv and argc with optind to jump over the arguments just consumed.

+4
source

This is the global variable used by getopt .

From the manual:

The getopt () function parses the command line arguments. Its arguments argc and argv are the arguments to count and array passed to the main () function when the program is called.

The optind variable is the index of the next item to process in argv. The system initializes this value to 1.

This code simply updates argc and argv to point to the rest of the arguments ( - options skipped).

+3
source

Regarding how:

optind is the number of argv elements that will be ignored after this code:

 argc -= optind; // reduces the argument number by optind argv += optind; // changes the pointer to go optind items after the first one 

argc (count) decreases by optind

and the pointer to the first argv element is updated accordingly.

For reasons:

See Caroli's answer.

+2
source

while running this code you can execute it as. / executable _file: name -d some_argument

When getopt is called, it starts to scan what is written on the command line. argc = 3, argv [0] =. / executable_file: name argv [1] = - d argv [2] = some_argument. getopt will get option d of that time optind = 2, which is the index of the next ie argv [2]. Therefore, optind + argv will point to argv [2].

In general, optind will have the index of the following.

0
source

All Articles