Getopt- Passing string parameter for argument

前端 未结 2 1863
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 18:33

I have a program which takes in multiple command line arguments so I am using getopt. One of my arguments takes in a string as a parameter. Is there anyway to obtain that st

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 18:52

    To specify that a flag requires an argument, add a ':' right after the flag in the short_opt variable. To use long arguments, use getopt_long().

    Here is a quick example program:

    #include 
    #include 
    
    int main(int argc, char * argv[]);
    
    int main(int argc, char * argv[])
    {
       int             c;
       const char    * short_opt = "hf:";
       struct option   long_opt[] =
       {
          {"help",          no_argument,       NULL, 'h'},
          {"file",          required_argument, NULL, 'f'},
          {NULL,            0,                 NULL, 0  }
       };
    
       while((c = getopt_long(argc, argv, short_opt, long_opt, NULL)) != -1)
       {
          switch(c)
          {
             case -1:       /* no more arguments */
             case 0:        /* long options toggles */
             break;
    
             case 'f':
             printf("you entered \"%s\"\n", optarg);
             break;
    
             case 'h':
             printf("Usage: %s [OPTIONS]\n", argv[0]);
             printf("  -f file                   file\n");
             printf("  -h, --help                print this help and exit\n");
             printf("\n");
             return(0);
    
             case ':':
             case '?':
             fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
             return(-2);
    
             default:
             fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
             fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
             return(-2);
          };
       };
    
       return(0);
    }
    

提交回复
热议问题