目录
1.引言
c语言的main函数的形式,一般为
int main(int argc, char* argv[[])
假如编译程序生产的可执行程序为target。则终端控制台运行时输入的一般形式如下
./target -选项1 参数1 -选项2 参数2。。。
argc为输入控制台的以空格分隔后的字符串的个数,argv为选项字符串的数组,其具体的数值,一般为空格分隔后的字符串数组。
2.getopt库函数
功能
getopt() 方法是用来分析命令行参数的,该方法由 Unix 标准库提供
头文件
<unistd.h>
函数模型
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopgetopt
入力参数:
argc:通常由 main 函数直接传入,表示参数的数量
argv:通常也由 main 函数直接传入,表示参数的字符串变量数组
optstring:一个包含正确的参数选项字符串,用于参数的解析。
例如 “abc:”,其中 -a,-b 就表示两个普通选项,-c 表示一个必须有参数的选项,因为它后面有一个冒号
外部变量:
optarg:如果某个选项有参数,这包含当前选项的参数字符串
optind:argv 的当前索引值
opterr:正常运行状态下为 0。非零时表示存在无效选项或者缺少选项参数,并输出其错误信息
optopt:当发现无效选项字符时,即 getopt() 方法返回 ? 字符,optopt 中包含的就是发现的无效选项字符
3.getopt的使用demo
#include<stdio.h>
#include<unistd.h>
int main(int argc, char* argv[])
{
int ret = 0;
printf("argc:%d\n",argc);
printf("argv:%s\n",argv[0]);
const char* optString = "abc:";
while((ret = getopt(argc, argv, optString)) != -1)
{
printf("getopt's ret is a:%c\n",(char)ret);
switch (ret)
{
case 'a':
printf("getopt's ret is a:%s\n",optarg);
break;
case 'b':
printf("getopt's ret is b:%s\n",optarg);
break;
case 'c':
printf("getopt's ret is c:%s\n",optarg);
break;
default:
break;
}
}
return 0;
}
ubuntu系统下的编译命令
gcc string_demo.cpp -o string_demo
编译成功后运行
./string_demo -a 1 -b 2 -c 5
log结果如下
root@xuehaiyang:/mnt/hgfs/99_github/cpp_demo# ./string_demo -a 1 -b 2 -c 5
argc:7
argv:./string_demo
getopt's ret is a:a
getopt's ret is a:(null)
getopt's ret is a:b
getopt's ret is b:(null)
getopt's ret is a:c
getopt's ret is c:5