相关库函数 #include <unistd.h> #include <getopt.h> int getopt(int argc, char * const argv[],const char *optstring); extern char *optarg; extern int optind, opterr, optopt; int getopt_long(int argc, char * const argv[],const char *optstring,const struct option *longopts, int *longindex); int getopt_long_only(int argc, char * const argv[],const char *optstring,const struct option *longopts, int *longindex);
eg1:
#include <stdio.h>
#include <getopt.h>
int main(int argc,char *argv[]) {
int opt;
char *optstring = "a:b:c:de"; // 分别代表-a,-b,-c,-d,-e命令行参数,其中带:的表示参数可以指定值,故de不能指定值
while((opt = getopt(argc,argv,optstring)) != -1){
printf("opt = %c\n",opt);
printf("optarg = %s\n",optarg);
printf("optind = %d\n",optind);
printf("argv[optind-1] = %s\n\n",argv[optind-1]);
}
return 0;
}
#./test_arg -a 1 -b 2 -c 3 -d -e
opt = a
optarg = 1
optind = 3
argv[optind-1] = 1
opt = b
optarg = 2
optind = 5
argv[optind-1] = 2
opt = c
optarg = 3
optind = 7
argv[optind-1] = 3
opt = d
optarg = (null)
optind = 8
argv[optind-1] = -d
opt = e
optarg = (null)
optind = 9
argv[optind-1] = -e本文出自 “程序员发展之路” 博客,请务必保留此出处http://xwandrew.blog.51cto.com/2909336/1971684
原文地址:http://xwandrew.blog.51cto.com/2909336/1971684