Search code examples
cgetopt

getopt adding extra functionality in C


here is my question. I want to be able to support this in my application:

./cipher [-devh] [-p PASSWD] infile outfile

I managed to get the [-devh] supported, but I don't know how to get [-p PASSWORD] supported. Of course I can manually check for argc being 2 and then have a bunch of flags but I prefer using getopts and think it would be easier. Here is my code for the [-devh] how can I extend it so it can support them remaining?

while ( (c = getopt(argc, argv, "devh")) != -1) {
    switch (c) {
    case 'd':
        printf ("option d\n");
        dopt = 1;
        break;
    case 'e':
        printf ("option e\n");
        eopt = 1;
        break;
    case 'v':
        printf ("option v\n");
        vopt = 1;
        break;
    case 'h':
        printf ("option h\n");
        hopt = 1;
        break;

    default:
        printf ("?? getopt returned character code 0%o ??\n", c);
    }
}

Solution

  • Taken directly from the GNU C Library Reference page on getopt:

    while ((c = getopt (argc, argv, "abc:")) != -1)
        switch (c)
        {
            case 'a':
                aflag = 1;
                break;
            case 'b':
                bflag = 1;
                break;
            case 'c':
                cvalue = optarg;
                break;
            case '?':
                if (optopt == 'c')
                    fprintf (stderr, "Option -%c requires an argument.\n", optopt);
                else if (isprint (optopt))
                    fprintf (stderr, "Unknown option `-%c'.\n", optopt);
                else
                    fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
                return 1;
            default:
                abort();
        }
    

    c here is the argument that takes an optional parameter, so this is probably the syntax you were looking for.

    What I understand getopt does is loop through the given arguments, parsing them one at a time. So when it gets to the option c (in your case p) where a second argument is required, it is stored in optarg. This is assigned to a variable of your choice (here cvalue) for later processing.