Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1879854
  • 博文数量: 217
  • 博客积分: 4362
  • 博客等级: 上校
  • 技术积分: 4180
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-20 09:31
文章分类

全部博文(217)

文章存档

2017年(1)

2015年(2)

2014年(2)

2013年(6)

2012年(42)

2011年(119)

2010年(28)

2009年(17)

分类: C/C++

2011-07-28 15:26:58

    记得自己原先写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()函数,这个函数我没有使用过,估计和这个差不多吧~~


阅读(1608) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~