问题是 select_index 没有被 getopt_long()更新,因此我无法以 long_options的形式访问正确的struct成员[option_index] .name 等。
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
int main(int argc, char** argv) {
int opt=0;
int option_index=0;
struct option long_options[]={
{"first", required_argument, NULL, 'f'},
{"second", no_argument, NULL, 's'},
{"third", required_argument, NULL, 't'},
{NULL, 0, NULL, 0}
};
while (1){
option_index=0;
opt=getopt_long (argc,argv, "f:st:", long_options, &option_index);
if ( opt == -1 )
break;
printf("option %s", long_options[option_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
}
return EXIT_SUCCESS;
}
输出:
# ~/workspace/Test/Debug/Test -f 1 -s -t third
option first with arg 1
option first
option first with arg third
在此先感谢,任何想法/领导将不胜感激!