Search code examples
cgetopt

how to printout help text using getopt in C?


I have a question about use getopt with command with the following code:

void createFunction()
{
   printf("create function\n");
}

void printHelp()
{
   printf("print help info\n");
}

const struct option long_opts[] = {{"help", no_argument, NULL, HELP},
                                   {"c",    no_argument ,NULL, CREATE_OPTION},
                                   {NULL,   0,           NULL, 0}};

while((opt = getopt_long_only(argc, argv, "", long_opts, NULL)) != -1)
{
    switch(opt) {
        case HELP:
            printHelp();
            break;
        case CREATE_OPTION:
            createFunction();
            break;
        default:
            printf("type base --help for details\n");
    }
}

how to printout the help text when type command without any parameters or with any faulty parameters, for example: only type command(in my case is "base") to trigger a printout of the help text? or command "base --" will trigger help text? Can anyone help?


Solution

  • You can use '?' case to trigger when an unrecognized option is passed :

    case '?':
        printf("Unknown option `-%c'.\n", optopt);
        printHelp();
        break;