小智 7
getopt将帮助您解析命令行参数.
getopt: -
在getopt手册页中,
句法 :
int getopt(int argc, char * const argv[], const char *optstring);
Run Code Online (Sandbox Code Playgroud)
getopt()函数解析命令行参数.它的参数argc和argv是在程序调用时传递给main()函数的参数count和数组.argv的一个元素以' - '开头(并且不完全是" - "或" - ")是一个选项元素.这个元素的字符(除了最初的' - ')是选项字符.如果重复调用getopt(),它将连续返回每个选项元素中的每个选项字符.
例:-
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
nsecs = 0;
tfnd = 0;
flags = 0;
while ((opt = getopt(argc, argv, "nt:")) != -1) {
switch (opt) {
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi(optarg);
tfnd = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
if (optind >= argc) {
fprintf(stderr, "Expected argument after options\n");
exit(EXIT_FAILURE);
}
printf("name argument = %s\n", argv[optind]);
/* Other code omitted */
exit(EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)
尝试使用getopt(3)手册页的链接来阅读有关getopt函数的更多信息.