【发布时间】:2013-03-06 04:43:16
【问题描述】:
我需要我的程序从命令行获取几个参数,语法如下:
getpwd -l user1 user2 ... -L -X -S...
所以,我需要让-l 选项背后的用户。我尝试使用getopt,但运气不佳,它仅在我将其他选项放在-l 之前才有效:
getpwd -L -X -S ... -l user1 user2 ...
我的代码(-l 和 -S):
while((c = getopt(argc, argv, "l:S")) != -1){
switch(c){
case 'l':
index = optind-1;
while(index < argc){
next = strdup(argv[index]); /* get login */
index++;
if(next[0] != '-'){ /* check if optarg is next switch */
login[lcount++] = next;
}
else break;
}
break;
case 'S':
sflag++; /* other option */
break;
case ':': /* error - missing operand */
fprintf(stderr, "Option -%c requires an operand\n", optopt);
break;
case '?': /* error - unknown option */
fprintf(stderr,"Unrecognized option: -%c\n", optopt);
break;
}
}
optopt 和 optind 是 extern int。
所以,问题是:我可以使用getopt() 函数(或getopt_long())吗?还是我必须编写自己的解析器才能得到我需要的东西?
【问题讨论】:
-
如果您对每个
-l一个用户没问题,您可以让用户根据需要使用尽可能多的-l选项。 -
遗憾的是,该程序的规范说它必须与每个
-l的多个用户一起使用
标签: c parsing command-line-arguments