【发布时间】:2011-06-15 08:43:04
【问题描述】:
我已阅读 a getopt() example,但它没有显示如何接受整数作为参数选项,例如示例代码中的 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) 吗?我尝试过不使用getopt() 直接访问argv[whatever] 并将其转换为整数,但在使用%d 打印时总是得到一个很大的负数。我假设我没有正确取消引用 argv[] 或其他什么,不确定...
【问题讨论】:
标签: c command-line-arguments getopt