0
下面的C代码工作正常,但我怎么知道用户是否已通过选项-d或不?如何知道特定的optarg选项是否通过c
从下面的代码,我就能知道,只有当用户使用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");
:
:
:
如果(0 == strnlen(argv的[I]中, “-d”,2)),你能解释这种烧焦字符串,以便列表代码行? – programmer
@programmer,'strlen()'的手册页有一个非常好的解释,但是,为了简单起见,比较'argv [i]'指向的char数组的前2个字节与字符串“-d”如果它们匹配,则输入'if()'的主体 – user3629249