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 entire source except:
argc -= optind;
argv += optind;
I know what is argc and argv, but what happen them in these two lines, what is “optind”
Explain me.
Thank you.
The
getoptlibrary provides several function to help parsing the command line arguments.When you call
getoptit “eats” a variable number of arguments (depending on the type of command line option); the number of arguments “eaten” is indicated in theoptindglobal variable.Your code adjusts
argvandargcusingoptindto jump the arguments just consumed.