mardi 11 mai 2021

Multiple options and multiple arguments per option using getopt()

I am trying to write a program that will take input from the command line similar to -l string string -la string using getopt() (an argument is not required as well, so could look like -l -la string), but appear to be running into issues when trying to implement a solution that would allow multiple options as well as multiple arguments per option if desired.

Here is a rough skeleton of what I have so far, excluding extraneous information, this will adequately accept a single option string (i.e. -l or -la or -al) with multiple arguments, but it will ignore any options after the arguments (i.e. in -l string string -la it will ignore the -la).

int main(int argc, char * argv[]) {
    int r;
    flags args;

    while ((r = getopt(argc, argv, "alf")) != -1) {
        switch(r) {
            case 'a':
                args.a = 1;
            break;

            case 'f':
                args.f = 1;
            break;

            case 'l':
                args.l = 1;
            break;

            case '?':
            
            break;

            default:
                abort();
        }
    }

    if (argc > optind && argv[optind][0] != '-')
        while (argc > optind)
            args.input.push_back(argv[optind++]);

    return 0;
}

I presume I will potentially need a vector of "flags" to store the different combinations of options and arguments, but for brevity, I figured it best to not implement it quite yet. If anyone has any ideas, that would be lovely, and please feel free to rip this code apart, I am sure there is some terrible practices in it.

Aucun commentaire:

Enregistrer un commentaire