getopt() 对命令行参数进行分析
getopt() 对命令行参数进行分析
例子:#include <stdio.h> #include <unistd.h>#include <stdlib.h>int main(int argc, char *argv[]){ int o; extern int optind, optopt, opterr; extern char *optarg; opterr = 0; while((o = getopt(argc, argv, "f:e:a")) != -1){ switch(o){ case 'f': fprintf(stderr, "f %s \n", optarg); break; case 'e': fprintf(stderr, "e %s\n", optarg); break; case 'a': fprintf(stderr, "a %s\n", optarg); break; case '?': if (optopt == 'f' || optopt == 'e') 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: printf("Unknown option characte"); abort (); } }}?需要注意的是:变量optind, optopt, opterr, optarg 都是全局变量, 外部引用, 定义时都需要加"extern""f:e:a"表示-f和-e有参数, -a没有参数, 编译为test,并测试# ./test -a 'abc' -f "abc" -e 'abc'a (null)f abc e abc# ./test -a 'abc' -f "abc" -e a (null)f abc Option -e requires an argument.?不过, 这样的代码还在存在问题,假如" -f"后面缺少参数, 它会误把"-e"当作"-f"的参数# ./test -a 'abc' -f -e "abc"a (null)f -e?