处理:
第二个参数有些东西: :后面须接参数 -bxx和:: 后面可不接参数,后面多个选项,-mnzxc
argv[optind]:可以得到后面 -axx -bxx 后面这个-bxx的值,不过是string类型的.
optarg:得到是-a后面的值.
#include <stdio.h> #include <unistd.h> #include "task.h" int main(int argc,char**argv) { int ch = -1; char *string = "v::a::b::cdezgnmcv"; int count = 0; while((ch=getopt(argc,argv,string))!=-1) { printf(" is %c ",ch); printf("gain is %s ",optarg); printf("optind is %d ",optind); printf("string optind is %s ",argv[optind]); printf("argc is %d ",argc); printf("argv is %s ",argv[1]); switch(ch) { case 'a': printf("get opt ch is a "); break; case 'b': printf("get opt ch is b "); break; case 'c': printf("get opt ch is c "); break; case 'd': printf("get opt ch is d "); break; case 'n': printf("get opt is n "); break; case 'v': printf(" string string gain is %s ",optarg); break; default: printf("unknow "); break; } count++; printf("count is %d ",count); } count = 0; //printf("argc backward is %d ",argc); //task_create(); //printf("argc forward is %d ",argc); while(1) { if( getchar() == 'x') { printf("main phread "); break; } } return 0; }
./sunshine -v500 -b11
is v
gain is 500
optind is 2
string optind is -b11
argc is 3
argv is -v500
string string gain is 500
count is 1
is b
gain is 11
optind is 3
string optind is (null)
argc is 3
argv is -v500
get opt ch is b
count is 2
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "task.h" int main(int argc,char**argv) { int ch = -1; char *string = "v::a::b::cdezgnmcv"; int count = 0; int volume = -1; while((ch=getopt(argc,argv,string))!=-1) { printf(" is %c ",ch); printf("gain is %s ",optarg); printf("optind is %d ",optind); printf("string optind is %s ",argv[optind]); printf("argc is %d ",argc); printf("argv is %s ",argv[1]); volume = strtol(optarg, NULL, 10); volume = atoi(optarg); printf("111111volume is1111111 %d ",volume); switch(ch) { case 'a': printf("get opt ch is a "); break; case 'b': printf("get opt ch is b "); break; case 'c': printf("get opt ch is c "); break; case 'd': printf("get opt ch is d "); break; case 'n': printf("get opt is n "); break; case 'v': printf(" string string gain is %s ",optarg); break; default: printf("unknow "); break; } count++; printf("count is %d ",count); } count = 0; //printf("argc backward is %d ",argc); //task_create(); //printf("argc forward is %d ",argc); while(1) { if( getchar() == 'x') { printf("main phread "); break; } } return 0; }