尝试程序中利用输入获取命令参数,如下程序:
#include <stdio.h>
#include <unistd.h>
int main()
{
int argc = 2;
char *argv[10];
int oc;
argv[0] = "help";
argv[1] = "-l";
while((oc = getopt(argc,argv,"l")) != -1)
{
switch(oc)
{
case 'l':
printf("help long option\n");
break;
default:
printf("error option\n");
break;
}
}
printf("%d\n",optind);
argc = 2;
argv[0] = "help";
argv[1] = "-s";
optind = 0;
while((oc = getopt(argc,argv,"l")) != -1)
{
switch(oc)
{
case 'l':
printf("help long option\n");
break;
case '?':
printf("help error option\n");
break;
default:
printf("error option\n");
break;
}
}
return 0;
}
char *optarg——当前选项参数字串(如果有)。
int optind——argv的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字串视为操作数,在argv[optind]至argv[argc-1]中可以找到。
int opterr——这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。
int optopt——当发现无效选项字符之时,getopt()函数或返回'?'字符,或返回':'字符,并且optopt包含了所发现的无效选项字符
需要清除。
getopt和getopt_long函数的使用方法转
http://blog.csdn.net/mr_jj_lian/article/details/6835137
http://blog.csdn.net/mr_jj_lian/article/details/6835352