我已经阅读了一个 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
的类型为char *
,我能否将optarg
强制转换为(int)
?我尝试过直接访问argv[whatever]
并将其转换为整数,但在使用%d
打印时,总是得到一个很大的负数。我猜想我没有正确引用argv[]
或者做了一些其他错误,但不确定…