int main(int argc, char *argv[])主函数中具有两个参数,整形argc和字符指针argv。
argc ------- 命令行参数的总个数,包括执行的程序名称。
argv[i] ------- 表示第i个参数,argv[0]就是执行的程序名称。
例子:
#include<stdio.h>
#include<unistd.h>
int main(int argc, int *argv[])
{
int i ;
printf("argc is %d\n",argc);
for(i=0;i<argc;i++)printf("argv[%d] is %s\n",i,argv[i]);
}
编译后文件名为test,输出结果:
getopt 是一个分析命令行函数,在表头文件<unistd.h>中,一般是在UNIX系统下使用。
定义的函数为:int getopt(int argc, char const *argv[],const char * optstring);
optstring是getopt()的短参数列表,如“abc:d::”。
上面的a为不带值得参数;b是必须带值得参数,因为参数后面多加了一个冒号;而c则是可选值得参数,它后面加了两个冒号。
实际调用的时候,“-a -b -c cvalue -ddvalue”这样用,不带值得参数可以连写,如"-ab",参数部分先后顺序,但是要记得可选值参数的值和参数之间不能有空格,例如d参数。
getopt的全局变量
optarg ------- 指向当前参数所带的值的指针
optind -------- 再次调用getopt()时下个argv指针的索引
optopt -------- 最后一个未知的选项
参考百度百科的实例:
#include<stdio.h>
#include<unistd.h>
int main(int argc,char **argv)
{
int ch;
opterr = 0;
while((ch = getopt(argc,argv,”a:bcde”))!= -1)
{
switch(ch)
{
case ‘a’: printf(“option a:’%s’\n”,optarg); break;
case ‘b’: printf(“option b :b\n”); break;
default: printf(“other option :%c\n”,ch);
}
printf(“optopt +%c\n”,optopt);
}
}
执行 $./getopt –boption b:b
执行 $./getopt –c
other option:c
执行 $./getopt –a
other option :?
执行 $./getopt –a12345
option a:’12345’