我已经阅读了一个 getopt() 示例,但它没有显示如何接受整数作为参数选项,就像cvalue
示例中的代码一样:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c':
cvalue = optarg;
break;
case '?':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
printf ("aflag = %d, bflag = %d, cvalue = %s\n",
aflag, bflag, cvalue);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
如果我按照上面的方式运行testop -c foo
,cvalue
将会是foo
,但是如果我想要testop -c 42
呢?既然cvalue
is 的类型char *
,我可以直接optarg
转换为 be(int)
吗?我试过这样做而不直接使用getopt()
和访问argv[whatever]
,并将其转换为整数,但在使用%d
. 我假设我没有argv[]
正确取消引用或其他东西,不确定......