#space after optional optarg?

9 messages · Page 1 of 1 (latest)

static peak
#

If you use getopt() to recieve arguments you can use flags (-e, -d etc). With a semicolon ( -e: ) the flag requires another argument, like this ./nice -e foo

With a double semicolon ( -e:: ) you can have an optional flag argument, but you have to write like this ./nice -efoo

Why did the space disappear and can I get it back?

celest furnaceBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

rain gyro
#

Let me scrape together the most important pieces of the code-puzzle so you can see how I did it (a few years ago 🐒 )

#
#include <string.h>
#include <stdio.h>
#include <getopt.h>
#include <ctype.h>

#define EQUALS(name, l, s, cl, cs) (!strcmp(name, l) || !strcmp(name, s) || !strcmp(name, cl) || !strcmp(name, cs))
#define SELECT_PARAM optarg ? optarg : (optind < argc ? argv[optind] : "")

int convertOptionNameToChar(char *name) {
    for (char *p = name; *p; ++p) *p = tolower(*p);

    if EQUALS(name, "help", "h", "-help", "-h")
        return 'h';
    else if EQUALS(name, "encode", "e", "-encode", "-e")
        return 'e';
    else if EQUALS(name, "decode", "d", "-decode", "-d")
        return 'd';
    else
        return '?';
}

int main(int argc, char *argv[]) {

    static const struct option long_options[] =
            {
                    {"help", no_argument, 0, 'h'},
                    {"encode", no_argument, 0, 'e'},
                    {"decode", no_argument, 0, 'd'},
                    0
            };


    int index = -1;
    char *filename;

    int result = getopt_long_only(argc, argv, "h::e:d:", long_options, &index);

    if (result != -1) {

        int param = 0;

        switch (result) {
            default:
            case '0':
            case '?':
                param = convertOptionNameToChar("");
                /* FALLTHRU */
            case 'h':
                if (!param)
                    param = convertOptionNameToChar(SELECT_PARAM);

                help(param, argv[0]);
                return 0;
            case 'e':
                filename = SELECT_PARAM;

                encode(filename);
                return 0;
            case 'd':
                filename = SELECT_PARAM;

                decode(filename);
                return 0;
        }
    }

    ...
}
static peak
#

Haha I shouldn't have skimmed through the manual, didn't see that one

#

Yeah getopt_long works

#

kinda weird getopt reads optional args differently tho

#

!solved