linux getopt()函数简单使用

来源:互联网 发布:c语言水仙花数代码 编辑:程序博客网 时间:2024/06/07 06:04
    记得自己原先写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

上一篇:erlang中io:format数据类型

下一篇:有意思的shell命令行提示符

相关热门文章
  • test123
  • 编写安全代码——小心有符号数...
  • 彻底搞定C语言指针详解-完整版...
  • 使用openssl api进行加密解密...
  • 一段自己打印自己的c程序...
  • linux dhcp peizhi roc
  • 关于Unix文件的软链接
  • 求教这个命令什么意思,我是新...
  • sed -e "/grep/d" 是什么意思...
  • 谁能够帮我解决LINUX 2.6 10...
给主人留下些什么吧!~~
原创粉丝点击