getopt----解析命令选项及参数
2017-09-21 09:57
531 查看
形式:
int getopt(argc,argv,”参数列表”);
int getopt(int argc, char *const argv[],const char *optstring);
调用一次,返回一个选项。在命令行选项参数再也检查不到optstring 中包含的选项时,返回-1,同时optind储存第一个不包括选项的命令参数。
何为 选项 ,参数**
字符串 optstring 可以下列元素
1.但个字符,表示选项
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。 参数紧跟着在选项后面或者以空格隔开。该参数的指针赋给optarg.
3.单个字符后跟两个冒号::,表示该选项后必跟一个参数。参数必须紧跟在选项后,不能以空格隔开。该参数的指针赋给optarg.
4.默认情况下,getopt会重新排列命令参数的顺序,所以到最后所有不包括选项的命令参数都排到最后。
getopt处理以“-”开头的命令行参数,optstring=”ab:c::d::”,命令行为getopt.exe -a -b host -ckeke -d haha
如: getopt.exe -a ima -b host -ckeke -d haha
-a,-b host,-ckeke, ima -d haha
解析:
extern char *optarg ;//选项的参数指针
extern int optind;//下次调用getopt,从optind存储的位置重新开始检查选项
extern int opterr,//pterr=0,getopt不向stderr输出错误信息
extern int optopt;//当命令行选项字符不包括在optstring 中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回“?“
例题
include
int main(int argc,char **argv)
{
int ch;
opterr = 0;
while((ch = getopt(argc,argv,”a:bcde”))!= -1)
{
switch(ch)
{
case ‘a’: printf(“option a:’%s’\n”,optarg); break;
case ‘b’: printf(“option b :b\n”); break;
default: printf(“other option :%c\n”,ch);
}
printf(“optopt +%c\n”,optopt);
}
}
执行 $./getopt –b
option b:b
执行 $./getopt –c
other option:c
执行 $./getopt –a
other option :?
执行 $./getopt –a12345
option a:’12345’
int getopt(argc,argv,”参数列表”);
int getopt(int argc, char *const argv[],const char *optstring);
调用一次,返回一个选项。在命令行选项参数再也检查不到optstring 中包含的选项时,返回-1,同时optind储存第一个不包括选项的命令参数。
何为 选项 ,参数**
字符串 optstring 可以下列元素
1.但个字符,表示选项
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。 参数紧跟着在选项后面或者以空格隔开。该参数的指针赋给optarg.
3.单个字符后跟两个冒号::,表示该选项后必跟一个参数。参数必须紧跟在选项后,不能以空格隔开。该参数的指针赋给optarg.
4.默认情况下,getopt会重新排列命令参数的顺序,所以到最后所有不包括选项的命令参数都排到最后。
getopt处理以“-”开头的命令行参数,optstring=”ab:c::d::”,命令行为getopt.exe -a -b host -ckeke -d haha
如: getopt.exe -a ima -b host -ckeke -d haha
-a,-b host,-ckeke, ima -d haha
解析:
extern char *optarg ;//选项的参数指针
extern int optind;//下次调用getopt,从optind存储的位置重新开始检查选项
extern int opterr,//pterr=0,getopt不向stderr输出错误信息
extern int optopt;//当命令行选项字符不包括在optstring 中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回“?“
例题
include
int main(int argc,char **argv)
{
int ch;
opterr = 0;
while((ch = getopt(argc,argv,”a:bcde”))!= -1)
{
switch(ch)
{
case ‘a’: printf(“option a:’%s’\n”,optarg); break;
case ‘b’: printf(“option b :b\n”); break;
default: printf(“other option :%c\n”,ch);
}
printf(“optopt +%c\n”,optopt);
}
}
执行 $./getopt –b
option b:b
执行 $./getopt –c
other option:c
执行 $./getopt –a
other option :?
执行 $./getopt –a12345
option a:’12345’
相关文章推荐
- Linux命令选项及参数解析 getopt() getopt_long() 函数
- 解析命令行选项参数函数getopt()
- 使用getopt_long解析程序长选项参数
- 使用getopt_long解析程序长选项参数
- 使用 getopt 处理命令行长参数(长选项)
- 使用getopt解析程序的参数选项
- 使用getopt命令解析shell脚本的命令行选项 【转】
- 使用getopt命令解析shell脚本的命令行选项
- 使用getopt命令解析shell脚本的命令行选项
- linux学习之命令参数解析——getopt()函数
- Linux解析命令行选项参数getopt和getopt_long
- 使用getopt命令解析shell脚本的命令行选项
- getopt_long()解析命令行选项参数
- getopt解析命令行选项参数
- python 解析输入的选项和参数
- 使用getopts命令解析shell脚本的命令行选项
- nutch2.3命令参数解析
- python采用getopt解析命令行输入参数实例
- caffe 命令及参数解析
- 命令调用C#程序, 路径参数解析错误