【发布时间】:2017-09-18 15:10:22
【问题描述】:
下面的 C 代码可以正常工作,但是我如何知道用户是否通过了选项 -d ?
从下面的代码我可以知道,只有当用户使用 optarg -d 选项时
Eg : ./application -d
只有这样代码才有效!
如果用户进入
./application -a
那我不知道选项 -d 是否通过。
另外选项 -a 应该取多个值,但下面的代码仅适用于单个值
eg : ./application -a knn , lr , ln
我怎样才能让这段代码接受同一个选项的多个值?
以下代码适用于单个值
eg : ./application -a knn
int main(int argc, char *argv[]) {
int opt= 0;
int start = -1, end = -1;
char *alg,*dir,*graph;
//Specifying the expected options
//The two options s and e expect numbers as argument
static struct option long_options[] = {
{"start",no_argument,0,'s' },
{"end",no_argument,0,'e' },
{"algorithm",no_argument, 0,'a' },
{"directory",required_argument, 0,'d' },
{"graph",required_argument,0,'g' },
{0,0,0,0}
};
int long_index =0;
int i=0,j=0;
size_t size = 1;
while ((opt = getopt_long(argc, argv,"s:e:a:d:h:g:",
long_options, &long_index )) != -1) {
switch (opt) {
case 'd' :
dir = optarg;
if (optarg == NULL)
printf("d option is must");
else
{
printf("option -d value is must\n");
usage();
exit(EXIT_FAILURE);
}
break;
case '?':
if (optopt == ('d' || 'a' || 'g' || 's' || 'e'))
fprintf (stderr, "Option -%c reqd", optopt);
usage();
exit(EXIT_FAILURE);
case 'a' :
alg = optarg;
if(alg == "lr" || alg == "knn" || alg == "cart")
{
printf("you entered option -a \"%s\"\n",optarg);
}
else
{
printf("Wrong option -a value is passed\n");
:
:
:
【问题讨论】:
标签: c arguments command-line-arguments