zoukankan      html  css  js  c++  java
  • getopt( )和 getopt_long( )

    有关系统调用getopt:
    声明:
             #include <unistd.h>
             int getopt(int argc, char *const argv[], const char *optstring);

             extern char *optarg;
             extern int optind, opterr, optopt;

    使用方法:在while循环中反复调用,直到它返回-1。每当找到一个有效的选项字母,它就返回这个字母。如果选项有参数,就设置optarg指向这个参数。
    当程序运行时,getopt()函数会设置控制错误处理的几个变量:
    char *optarg ──如果选项接受参数的话,那么optarg就是选项参数。
    int optind──argv的当前索引,当while循环结束的时候,剩下的操作数在argv[optind]到argv[argc-1]中能找到。
    int opterr──当这个变量非零(默认非零)的时候,getopt()函数为"无效选项”和“缺少选项参数”这两种错误情况输出它自己的错误消息。可以在调用getopt()之前设置opterr为0,强制getopt()在发现错误时不输出任何消息。

    int optopt──当发现无效选项的进修,getopt()函数或者返回'?'字符,或者返回字符':'字符,并且optopt包含了所发现的无效选项字符。

    范例 #include<stdio.h>

    #include<unistd.h>
    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’
  • 相关阅读:
    (转)VC++多线程编程
    英文缩写汇总
    SINGLETON(单件)——对象创建型模式
    指针地址的修改
    我在csdn博客中的一些总结
    listener的执行先后问题
    css的精髓是布局,而不是样式——之三
    Jo——一个简单HTML5移动框架介绍
    深入了解javascript中的exec与match方法
    多ajax查询模拟一个整体的查询事务
  • 原文地址:https://www.cnblogs.com/ancient/p/3202157.html
Copyright © 2011-2022 走看看