Using `getopt` to take in multiple options after one hyphen

574 views Asked by At

So I am writing a small program that is supposed to implement a basic version of ls and takes in the optional flags a, l, and R. I have basically everything else covered, but, for the past week or so, I have not been able to figure out how to pass in multiple flags after one hyphen. For example, my program should be able to take in ls -alR. However, the code that I have for this (shown below and modified from getopt's man page) does not work in cases like these. Cases like ls -a -l -R work just fine.

Is getopt not able to handle these kind of options? Should I look into getopt_long or getopt_long_only, or even look at different libraries (for example boost options)?

//gloabl indicator variables
bool aflag, lflag, Rflag; 

//sets Truth values to boolean global indicator variables 
//will tell if a, l, or R flags passed into argv
//FIXME need to fix case(s) -alR,...
int main (int argc, char ** argv)
{       
        int index;
        int c;
        opterr = 0;

        while( (c = getopt (argc, argv, "alR")) != -1 )
        {
                switch (c)
                {
                        case 'a':
                                aflag = true;
                                break;
                        case 'l':
                                lflag = true;
                                break;
                        case 'R':
                                Rflag = true;
                                break;
                        case '?':
                                if (isprint (optopt))
                                  fprintf (stderr, "Unknown option `-%c'.\n", optopt); 
                        default:
                                abort ();
                }
        }

        // prints out truth values for flags
        printf ("aflag = %d, lflag = %d, Rflag = %d\n", aflag, lflag, Rflag);

        //prints out non option arguments   
        for (index = optind; index < argc; index++)
        printf ("Non-option argument %s\n", argv[index]);

        //DO OTHER STUFF
        return 0; 
}

I should add that these flags require no arguments. Thanks in advance!

0

There are 0 answers