1
static struct option long_options[] =
{
     {"r",   required_argument,  0, 'r'},
     {"help",        no_argument,        0, 'h'},
     {0, 0, 0, 0}
};


int option_index = 0;
char c;
while((c = getopt_long(argc, argv, "r:h", long_options, &option_index)) != -1)
{
    switch(c)
    {
        case 'r':
            break;
        case 'h':
            return EXIT_SUCCESS;
    }
}

How do I make h the default argument, so if this program is run without any arguments, it will be as if it was run with -h?

anc
  • 191
  • 1
  • 19

2 Answers2

1

Maybe try something like this:

static struct option long_options[] =
{
     {"r",    required_argument,  0, 'r'},
     {"help", no_argument,        0, 'h'},
     {0, 0, 0, 0}
};

int option_index = 0;
char c = getopt_long(argc, argv, "r:h", long_options, &option_index);
if (c == -1)
{
    // display help...
    return EXIT_SUCCESS;
}

do
{
    switch(c)
    {
        case 'r':
            break;

        case 'h':
        {
            // display help...
            return EXIT_SUCCESS;
        }
    }

    c = getopt_long(argc, argv, "r:h", long_options, &option_index);
}
while (c != -1);

Or this:

static struct option long_options[] =
{
     {"r",    required_argument,  0, 'r'},
     {"help", no_argument,        0, 'h'},
     {0, 0, 0, 0}
};

int option_index = 0;
char c = getopt_long(argc, argv, "r:h", long_options, &option_index);
if (c == -1)
    c = 'h';

do
{
    switch(c)
    {
        case 'r':
            break;

        case 'h':
        {
            // display help...
            return EXIT_SUCCESS;
        }
    }

    c = getopt_long(argc, argv, "r:h", long_options, &option_index);
}
while (c != -1);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

Why not create a printUsage function and do something like.

if (c == 0) {
    printUsage();
    exit(-1);
}