Home > Software engineering >  getopt() function: purpose of addition of argv
getopt() function: purpose of addition of argv

Time:02-14

code piece from book

I am reading getopt() funtion from a book and trying to make a program that takes command line arguments. But what is the purpose of adding optind to argv, and how to add an integer to pointer array? Full code:

#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[]){
    char *delivery = "";
    int thick = 0;
    int count = 0;
    char ch;
    
    while((ch = getopt(argc, argv, "td:")) != EOF)
        printf("%i\n", ch);
        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 delivered %s.\n", delivery);
        
    puts("Ingredients:");
    
    for(count = 0 ; count < argc ;   count)
        puts(argv[count]);
    return 0;
}

CodePudding user response:

optind is the index of the next parameter to manage on the command line. In other words, it is the number of parameters managed so far. The goal of adding optind to argv is to make it point to the possible remaining parameters behind the already managed options on the command line. Hence, those additional parameters will be in argv[0], argv[1]... up to argv[argc - 1] since argc has been decremented with optind.

The following loop displays those additional parameters on the command line:

for(count = 0 ; count < argc ;   count)
        puts(argv[count]);

If you don't add optind to argv and don't decrement argc with it, the previous loop would have been:

for(count = optind ; count < argc ;   count)
        puts(argv[count]);

N.B.: As argv is a pointer on a char *, adding to it some value like optind makes it be incremented by "optind x sizeof(char *)"

  • Related