Search code examples
cargp

How to accept a char or string as input


after reading a famous pdf about argp, I wanted to make something with it, but I'm having a problem, in this example:

static int parse_opt (int key, char *arg, struct argp_state *state)
{
    switch (key)
    {
        case 'd':
        {
            unsigned int i;
            for (i = 0; i < atoi (arg); i++)
                printf (".");
            printf ("\n");
            break;
        }
    }
    return 0;
}

int main (int argc, char **argv)
{
    struct argp_option options[] = 
    {
        { "dot", 'd', "NUM", 0, "Show some dots on the screen"},
        { 0 }
    };
    struct argp argp = { options, parse_opt, 0, 0 };
    return argp_parse (&argp, argc, argv, 0, 0, 0);
}

The -d accepts an argument of int type, but if I want to get a char or char array as an argument? The pdf doesn't covers that neither the docs.

I'm beginning to learn C, I know it in a basic way, I'm more familiar with other lenguages, so to learn more about it I want to archive this but I don'get it how can I make it accept a char array.

Code that didn't work when comparing arg with a char:

static int parse_opt(int key, char *arg, struct argp_state *state)
{       
    switch(key)
    {
        case 'e':
        {
            //Here I want to check if "TOPIC" has something, in this case, a char array
            //then based on that, do something.
            if (0 == strcmp(arg, 'e'))
            {
                printf("Worked");
            }
        }
    }

    return 0;
}//End of parse_opt

int main(int argc, char **argv)
{
    struct argp_option options[] = 
    {
        {"example", 'e', "TOPIC", 0, "Shows examples about a mathematical topic"},
        {0}
    };

    struct argp argp = {options, parse_opt};

    return argp_parse (&argp, argc, argv, 0, 0, 0); 
}//End of main

Thanks in advance.


Solution

  • https://www.gnu.org/software/libc/manual/html_node/Argp.html

    #include <stdio.h>
    #include <argp.h>
    #include <string.h>
    
    static int parse_opt(int key, char *arg, struct argp_state *state) {
      (void)state; // We don't use state
      switch (key) {
      case 'c': {
        if (strlen(arg) == 1) { // we only want one char
          char c = *arg;        // or arg[0]
          printf("my super char %c !!!\n", c);
        } else {
          return 1;
        }
      }
      }
      return 0;
    }
    
    int main(int argc, char **argv) {
      struct argp_option const options[] = {
          {"char", 'c', "c", 0, "a super char", 0}, {0}};
      struct argp const argp = {options, &parse_opt, NULL, NULL, NULL, NULL, NULL};
      argp_parse(&argp, argc, argv, 0, NULL, NULL);
    }