Linux下面有个函数可以解析命令,它就是getopt()函数,getopt函数的定义如下:
#include <unistd.h>
int getopt(int argc, char * const argv[],
const char *optstring);
argc是主函数中的参数argc,argv也是主函数中的参数,后面的optstring是getopt函数的最后一个参数,它是常字符串类型,由程序人员自己设定,通过swich、case来甄别输入的argv参数,常见的optstring有四种类型:
1、常操作方式:
int option = getopt(argc, argv, “mg”);
这里的m和g代表某种操作命令。
2、带有单冒号的操作方式:
int option = getopt(argc, argv, “mgf:”);
单引号的在这里的作用是表示f操作后面有选项,这里的选项是必须要输入的,且f和选项之间要空格隔开,否则会报错。
3、带有双引号的操作方式:
int option = getopt(argc, argv, “mgf:x::”);
双引号在这里的作用是表示x后面有可选项,这里的可选项和操作x之间不能有空格,否则也会报错。
以上三种方式可以同时使用,互不影响。
4、有错误输入输出’?’:
当输入的不是之前设置的argv参数时,在设置case时设置一个case ‘?’选项将会捕捉到你的错误输出。还有一种方式捕捉错误输入,那就是把’?’换为’:’。
getopt函数也有四个全局变量,它们分别作用如下:
(1)char *optarg——如果在argv参数中输入了带有单引号的操作,那么操作内容就保存在这个变量中,使用完系统会再次制空,代码中可以测试证实。
(2)int optind——argv的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字串视为操作数,在argv[optind]至argv[argc-1]中可以找到。
(3)int opterr——这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息;为0时,系统将不会自动输出错误原因。
(4)int optopt——当发现无效选项字符之时,getopt()函数或返回’?’字符,或返回’:’字符,并且optopt包含了所发现的无效选项字符。
以上三种方式可以同时出现,互不影响。在代码中我们会体现这三种操作方式。
下面是这个函数的使用展示:
#include<iostream>
#include<unistd.h>
using namespace std;
int main(int argc, char *argv[])
{
int option = 0;
while((option = getopt(argc, argv, "mgf:x::")) != -1)
{
switch(option)
{
case 'm':
cout<<"m is true."<<endl;
break;
case 'g':
cout<<"g is true."<<endl;
break;
case 'f':
cout<<"f is true"<<endl;
cout<<"f optarg is:>"<<optarg<<endl;
// optarg = NULL;//测试optarg
break;
case 'x':
cout<<"x is true"<<endl;
if(optarg != NULL)
cout<<"x optarg is :>"<<optarg<<endl;
break;
case '?':
cout<<"command is erro"<<endl;
break;
}
}
return 0;
}
结果: