linux getopt()函数简单使用

    记得自己原先写ls函数的时候,没有使用什么命令行参数处理函数,都是自己编写的函数实现的命令行参数的处理,今天在学习POSIX进程间通信的时候发现有一个函数getopt()其实就是专门来做这个事情的,把这个函数的使用简单总结一下吧。
    这个函数的定义如下:
         int getopt(int argc,char * const argv[ ],const char * optstring);
    这个函数包含在头文件 中,所以我们使用的时候,只须把这个头文件加进来就可以调用了。
    与这个函数相关的有3个全局变量,我们得学习一下。
        optarg——指向当前选项参数(如果有)的指针
        optind——再次调用 getopt() 时的下一个 argv 指针的索引
        optopt——最后一个已知选项
   关于着三个变量,自己写个程序看一下,看一看它们到底代表的是什么。下面是一个简单的程序:
  1. #include <unistd.h>
  2. #include <stdio.h>

  3. int main(int argc, char *argv[])
  4. {
  5.     int ch;
  6.     printf("%d %s\n", optind, optarg);
  7.     while((ch = getopt(argc, argv, "a:b::c:")) != -1) {
  8.         switch(ch) {
  9.             case 'a':
  10.                 printf("a:%s %d %d\n", optarg, optind, optopt);
  11.                 break;
  12.             case 'b':
  13.                 printf("b:%s %d %d\n", optarg, optind, optopt);
  14.                 break;
  15.             case 'c':
  16.                 printf("c:%s %d %d\n", optarg, optind, optopt);
  17.                 break;
  18.             default:
  19.                 break;
  20.         }
  21.     }
  22.     return 0;
  23. }
    我们再来看一下这个程序的执行:
  1. ^_^[sunny@sunny-laptop ~/c_test]13$ ./a.out -a aaa -bfan -c cccc
  2. 1  (null)
  3. a:aaa 3 0
  4. b:fan 4 0
  5. c:cccc 6 0
  6. ^_^[sunny@sunny-laptop ~/c_test]14$ ./a.out -b fan
  7. 1  (null)
  8. b:(null) 2 0
  9. ^_^[sunny@sunny-laptop ~/c_test]15$ ./a.out -a fan
  10. 1  (null)
  11. a:fan 3 0
  12. ^_^[sunny@sunny-laptop ~/c_test]16$ 
    程序说明:在getopt()的第三个参数实际上表示的是你所要求的命令行参数的格式要求,在本程序中的“a:b::c:”表示,参数是a,b,或者是c。“:”表示,需要一个空格,后面得再加一个参数,“::”表示后面不需要空格,得再加一个参数,所以现在的话,我们就能简单的使用这个很好的命令行参数处理函数了~
    另外,我们还有一个函数getopt_long()函数,这个函数我没有使用过,估计和这个差不多吧~~


<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(958) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值