参考书目:Linux/Unix系统编程手册 P1156
函数原型
#include <unistd.h>
int getopt(int argc, char * const argv[],
const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
其中的argc,argv为命令行参数,optstring为需要被getopt()寻找的命令行选项合集。举例说明”:x:p::”,开头的”:”表示禁止显示错误信息(opterr被重载为0),针对未识别的选项返回’?’,针对缺少参数的选项返回’:’。x后的’:’表示选项x必须带一个参数,p后的’::’表示选项p后的参数为可选参数。
通过连续调用getopt(),可以解析命令行参数。当getopt()返回值为-1时,说明到达了选项列表的结尾。如果选项带有参数,getopt()会把全局变量optarg指向这个参数。optind指向参数列表argv中未处理的下一个元素的索引。getopt()返回-1,表示参数列表argv中解析完毕,如果此时optind小于argc,那么argv[optind]表示命令行中下一个非选项单词。
测试代码
/*************************************************************************
> File Name: test.c
> Author: 0nism
> Mail: [email protected]
> Created Time: Mon 03 Sep 2018 06:57:11 PM CST
************************************************************************/
#include <ctype.h>
#include "tlpi_hdr.h"
#define printable(ch) (isprint((unsigned char) ch) ? ch : '#')
static void usageError(char * progName, char * msg, int opt)
{
if (msg != NULL && opt != 0)
fprintf(stderr, "%s (-%c)\n", msg, printable(opt));
fprintf(stderr, "Usage: %s [-p arg] [-x]\n", progName);
exit(EXIT_FAILURE);
}
int main(int argc, char * argv[])
{
int opt, xfnd;
char *pstr;
xfnd = 0;
pstr = NULL;
while ((opt = getopt(argc, argv, ":p:x")) != -1)
{
printf("opt =%3d (%c); optind = %d", opt, printable(opt), optind);
if (opt == '?' || opt == ':')
printf("; optopt =%3d (%c)", optopt, printable(optopt));
printf("\n");
switch (opt) {
case 'p': pstr = optarg; break;
case 'x': xfnd++; break;
case ':': usageError(argv[0], "Missing argument", optopt);
case '?': usageError(argv[0], "Unrecognized option", optopt);
default:
printf("Unexcepted case in switch()\n");
exit(EXIT_FAILURE);
}
}
if (xfnd != 0)
printf("-x was specified (count=%d)\n", xfnd);
if (pstr != NULL)
printf("-p was specified with the value \"%s\"\n", pstr);
if (optind < argc)
printf("First nonoption argument is \"%s\", at argv[%d]\n",
argv[optind], optind);
exit(EXIT_SUCCESS);
}
测试结果
[MISlike@iz2zeg66n0rz6nvtbg49j6z file_io]$ vim test.c
[MISlike@iz2zeg66n0rz6nvtbg49j6z file_io]$ gcc test.c -o test
[MISlike@iz2zeg66n0rz6nvtbg49j6z file_io]$ ./test -x -p hello world
opt =120 (x); optind = 2
opt =112 (p); optind = 4
-x was specified (count=1)
-p was specified with the value "hello"
First nonoption argument is "world", at argv[4]
[MISlike@iz2zeg66n0rz6nvtbg49j6z file_io]$ ./test -p
opt = 58 (:); optind = 2; optopt =112 (p)
Missing argument (-p)
Usage: ./test [-p arg] [-x]
[MISlike@iz2zeg66n0rz6nvtbg49j6z file_io]$ ./test -a
opt = 63 (?); optind = 2; optopt = 97 (a)
Unrecognized option (-a)
Usage: ./test [-p arg] [-x]
[MISlike@iz2zeg66n0rz6nvtbg49j6z file_io]$ ./test -p -x
opt =112 (p); optind = 3
-p was specified with the value "-x"