Search code examples
cgetoptsgetopt-long

Parsing options having a common flag in C


I have a C program where I accept multiple arguments. Here, I have a common flag d for both data-store and disk. Is there a way that I can check for the flags in-order and get the value of store before I check with case d. I've tried various ways like adding a while loop before this to check for s and then enter this loop etc.

static void
ParseOptions(int argc, char* argv[])
{
   int c, option_index;
   int ind = 0;

   while((c = getopt_long(argc, argv, "s:d:",
                          long_options, &option_index))!= -1) {
       ind = optind;
       switch(c) {
        case 's':
            optionStore = true;
            store = strdup(optarg);
            break;
        case 'd':
            if(strcmp(store,"datastore") == 0){
                printf("In datastore\n");
                datastore = strdup(optarg);
            }
            else if(strcmp(store,"disk") == 0){
                printf("In disk\n");
                disk = strdup(optarg);

            }            
            break;
        default:
            exit(-1);
       }
   }
}

Not sure how to go about this.


Solution

  • You need to store optarg returned for flag d in a temporary variable, and use it after the loop exits to set either disk or datastore:

    char *temp_disk_or_datastore;
    while((c = getopt_long(argc, argv, "s:d:",
                          long_options, &option_index))!= -1) {
        ind = optind;
        switch(c) {
            case 's':
                optionStore = true;
                store = strdup(optarg);
                break;
            case 'd':
                temp_disk_or_datastore = strdup(optarg);       
                break;
            default:
                exit(-1);
        }
    }
    if (store == NULL) {
        printf("Missing storage option");
        exit(-1);
    }
    if(strcmp(store,"datastore") == 0){
        printf("In datastore\n");
        datastore = temp_disk_or_datastore;
    }
    else if(strcmp(store,"disk") == 0){
        printf("In disk\n");
        disk = temp_disk_or_datastore;
    }