博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
getopt, optarg, optind, opterr, optopt
阅读量:6876 次
发布时间:2019-06-26

本文共 1186 字,大约阅读时间需要 3 分钟。

hot3.png

#include <unistd.h>

       int getopt(int argc, char * const argv[],

                  const char *optstring);

       extern char *optarg;

       extern int optind, opterr, optopt;

       #include <getopt.h>

       int getopt_long(int argc, char * const argv[],

                  const char *optstring,
                  const struct option *longopts, int *longindex);

       int getopt_long_only(int argc, char * const argv[],

                  const char *optstring,
                  const struct option *longopts, int *longindex);

getopt(): _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE

getopt_long(), getopt_long_only(): _GNU_SOURCE

 

getopt 用于解析命令行参数,如 -a -t -s0 等等

             optstring中后面的冒号表示需要接变量,并存于optarg中。如果接二个冒号,则表示变量可有可无。

             扫描模式:

                         1. 如果第一个字符为加号: 停止于发现第一个非选项

                         2. 如果第一个字符为减号:全部扫描;此为默认模式。

             碰到'--',则忽略扫描模式,必须停止扫描。

             返回值:

                          成功,返回option;

                          结束,返回-1;

                          发现不认识的option,返回?号

                          碰到option后面缺参数,则返回?号。

                                                                     或返回:号(optstring中第一个字符(如果有加减号,在加减号后面)为冒号时返回,即为:或+:或-:)。

 

optarg  存数据

optind,

opterr   控制是否向STDERR打印错误。为0,则关闭打印。

optopt  存储出错的option(如缺参数),或者不认识的option

 

摘自openssh的用法示例:

while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)

  switch (ch) {

  case '3':
   throughlocal = 1;
   break;

  case 'o':

   addargs(&args, "-%c", ch);

   addargs(&args, "%s", optarg);
   break;

 default:
   usage();
  }
 argc -= optind;
 argv += optind;

转载于:https://my.oschina.net/jacobin/blog/185314

你可能感兴趣的文章
redis 主从切换
查看>>
学会倾听-情商培养
查看>>
教你快速查找ARP病毒源技巧三则
查看>>
客户端不能连接mysql的问题
查看>>
向PLIST文件中追加数据
查看>>
exchange2007配置发送、接收附件大小
查看>>
iOS 索引列 使用详解
查看>>
我的友情链接
查看>>
centos 安装
查看>>
我的友情链接
查看>>
2014 工作计划
查看>>
装饰器
查看>>
http_proxy_module模块常用参数
查看>>
jsp中c标签的使用
查看>>
LINUX安装详解
查看>>
struts2+json(4)
查看>>
mongodb数据库特点(包括评论、点赞的数据库字段设计)
查看>>
渺小的自己
查看>>
我的友情链接
查看>>
用PHP读取和编写XML DOM5
查看>>