函数API

getopt()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <stdio.h> #include <unistd.h> #include <stdlib.h>
int main(int argc, char **argv) { int opt; int a_flag = 0, l_flag = 0; printf("argc = %d\n", argc); while((opt = getopt(argc, argv, "alm:o::")) != -1) { switch(opt) { case 'a': a_flag = 1; break; case 'l': l_flag = 1; break; case 'm': printf("msg = %s\n", optarg); break; case 'o': printf("opt = %s\n", optarg); break; default : fprintf(stderr, "Usage : %s -al\n", argv[0]); } }
printf("optind = %d\n optopt = %c\n", optind, optopt);
return 0; }
|
- getopt函数的第三个字符串参数 “$alm:o::$”:在man page中这样解释为:**-al 不用一个关联值;-m 需要有一个关联的value参数;-o 可以加一个关联参数也可以不加**。
运行结果:
1 2 3 4 5
| ➜ test ./a.out -t //首先 -t 是一个非法的选项 ./a.out: invalid option -- 't' //输出错误信息,因为非法选项 optind = 2 //此时argv[optind]是我们的操作数,也就是我们传递给主函数的参数 optopt = t //当发现无效项字符时,optopt会包含该字符,正如我们传递的‘a’这个无效项。 opterr = 1 //opterr变量非零,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。Usage : ./a.out -al
|
再次运行:
1 2 3 4 5
| ➜ test ./a.out -m //根据getopt函数的第三个参数,因为‘m’字符后有‘:’冒号,因此在‘-m’选项后需要跟随一个参数。因此此次运行的错误为“缺少参数”,如下提示: ./a.out: option requires an argument -- 'm' //输出了错误信息,因为“缺少参数” optind = 2 //argv[optind]为空,因为此次运行没有传递参数 optopt = m //当发现无效项字符时,optopt会包含该字符,正如我们传递的‘t’缺少参数的选项。 opterr = 1 //opterr变量非零,getopt()函数为“无效选项”和“缺少参数“选项,并输出其错误信息。Usage : ./a.out -al
|
再次运行:
1 2 3 4 5 6
| ➜ test ./a.out -al -m 123 -o //‘-al’不用加参数,‘-m’需要加参数,‘-o’可加可不加, 向main函数传递参数叫123、456 argc = 5 // 字符串长度 msg = 123 opt = 456 optind = 5 // 字符串长度 optopt =
|
外部变量
optind、opterr、optopt、optarg、errno
都在某个.c文件中定义的,所有现在能用,可能是外部变量、可能是静态全局变量… …
a.c
1 2 3 4 5 6 7 8 9 10
| #include <stdio.h>
void input(); extern int age;
int main() { input(); printf("ttw age : %d \n", age); return 0; }
|
b.c
1 2 3 4 5 6 7 8 9
| #include <stdio.h>
int age;
void input() { printf("Please input you age:\n\t"); scanf("%d", &age); return ; }
|
运行结果
1 2 3
| Please input you age: 14 ttw age : 14
|