getopt()
1、定义:
int getopt(int argc, char * const argv[], const char *optstring);
2、描述:
getopt是用来解析命令行选项参数的,但是只能解析短选项: -d 100,不能解析长选项:--prefix
3、参数:
argc:main()函数传递过来的参数的个数 argv:main()函数传递过来的参数的字符串指针数组 optstring:选项字符串,告知 getopt()可以处理哪个选项以及哪个选项需要参数
4、返回:
如果选项成功找到,返回选项字母;如果所有命令行选项都解析完毕,返回 -1;如果遇到选项字符不在 optstring 中,返回字符 '?';如果遇到丢失参数,那么返回值依赖于 optstring 中第一个字符,如果第一个字符是 ':' 则返回':',否则返回'?'并提示出错误信息。
5、下边重点举例说明optstring的格式意义:
char*optstring = “ab:c::”; 单个字符a 表示选项a没有参数 格式:-a即可,不加参数 单字符加冒号b: 表示选项b有且必须加参数 格式:-b 100或-b100,但-b=100错 单字符加2冒号c:: 表示选项c可以有,也可以无 格式:-c200,其它格式错误
上面这个 optstring 在传入之后,getopt 函数将依次检查命令行是否指定了 -a, -b, -c(这需要多次调用 getopt 函数,直到其返回-1),当检查到上面某一个参数被指定时,函数会返回被指定的参数名称(即该字母)
optarg —— 指向当前选项参数(如果有)的指针。 optind —— 再次调用 getopt() 时的下一个 argv指针的索引。 optopt —— 最后一个未知选项。 opterr —— 如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。
以上描述的并不生动,下边结合实例来理解:
6、实例:
#include<stdio.h>
#include<unistd.h>
#include<getopt.h>
int main(intargc, char *argv[])
{
int opt;
char *string = "a::b:c:d";
while ((opt = getopt(argc, argv, string))!= -1)
{
printf("opt = %c\t\t", opt);
printf("optarg = %s\t\t",optarg);
printf("optind = %d\t\t",optind);
printf("argv[optind] = %s\n",argv[optind]);
}
}
编译上述程序并执行结果:
输入选项及参数正确的情况
dzlab:~/test/test#./opt -a 100 -b 200 -c 300 -d
opt = a optarg = 100 optind = 2 argv[optind] = -b
opt = b optarg = 200 optind = 4 argv[optind] = -c
opt = c optarg = 300 optind = 6 argv[optind] = -d
opt = d optarg = (null) optind = 7 argv[optind] = (null)
之前做过一个电子书项目,开发过程中使用的是命令行测试
这里就是用了一个switch--case来判断,在调试中还算实用
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
/* ./show_file [-s Size] [-f freetype_font_file] [-h HZK] <text_file> */
//./show_file -s 16 -h HZK16 -f ./MSYH.TTF utf-8_book_test.txt
int main(int argc, char **argv)
{
int iError;
unsigned int dwFontSize = 16;
char acHzkFile[128];//汉子库字体文件
char acFreetypeFile[128];//Freetype字体文件
char acTextFile[128];//显示的文件文件
char acDisplay[128];//显示设备
char cOpr;
int bList = 0;//是否支持打印支持的显示设备、字体文件、编码文件标志
acHzkFile[0] = '\0';
acFreetypeFile[0] = '\0';
acTextFile[0] = '\0';
strcpy(acDisplay, "fb");//默认支持的显示设备
while ((iError = getopt(argc, argv, "ls:f:h:d:k")) != -1)
{
switch(iError)
{
case 'l'://支持显示打印
{
bList = 1;
break;
}
case 's'://字体大小
{
dwFontSize = strtoul(optarg, NULL, 0);
break;
}
case 'f'://freetype字体文件
{
strncpy(acFreetypeFile, optarg, 128);
acFreetypeFile[127] = '\0';
break;
}
case 'h'://汉字库字体文件
{
strncpy(acHzkFile, optarg, 128);
acHzkFile[127] = '\0';
break;
}
case 'd'://重新指定显示设备
{
strncpy(acDisplay, optarg, 128);
acDisplay[127] = '\0';
break;
}
default:
{
printf("iError:%d %c\n", iError, iError);
printf("Usage: %s [-s Size] [-d display] [-f font_file] [-h HZK] <text_file>\n", argv[0]);
printf("Usage: %s -l\n", argv[0]);
return -1;
break;
}
}
}
if (!bList && (optind >= argc))
{
printf("Usage: %s [-s Size] [-d display] [-f font_file] [-h HZK] <text_file>\n", argv[0]);
printf("Usage: %s -l\n", argv[0]);
return -1;
}
return 0;
}