html5中文学习网

您的位置: 首页 > 网络编程 > ASP.NET » 正文

getopt() 对命令行参数进行分析_.NET教程_编程技术

[ ] 已经帮助:人解决问题

getopt() 对命令行参数进行分析
int getopt( int argc, char *const argv[], const char *optstring );
        给定了命令参数的数量 (argc)、指向这些参数的数组 (argv) 和选项字符串 (optstring) 后,getopt() 将返回第一个选项,并设置一些全局变量。使用相同的参数再次调用该函数时,它将返回下一个选项,并设置相应的全局变量。如果不再有识别到的选项,将返回 -1,此任务就完成了。可以重复调用 getopt(),直到其返回 -1 为止.
getopt() 所设置的全局变量包括:
    optarg——指向当前选项参数(如果有)的指针。
    optind——再次调用 getopt() 时的下一个 argv 指针的索引。
    optopt——最后一个已知选项。
其中optstring 书写格式如下: "f:e:ac" , 其中':'表示前一个字符是带参数的
例子:
    #include <stdio.h>   
    #include <unistd.h> 
    #include <stdlib.h> 
     
    int main(int argc, char *argv[]){ 
        int o; 
        extern int optind, optopt, opterr; 
        extern char *optarg; 
     
        opterr = 0; 
        while((o = getopt(argc, argv, "f:e:a")) != -1){ 
            switch(o){ 
                case 'f': 
                    fprintf(stderr, "f %s /n", optarg); 
                    break; 
                case 'e': 
                    fprintf(stderr, "e %s/n", optarg); 
                    break; 
                case 'a': 
                    fprintf(stderr, "a %s/n", optarg); 
                    break; 
                case '?': 
                    if (optopt == 'f' optopt == 'e') 
                        fprintf (stderr, "Option -%c requires an argument./n", optopt); 
                    else if (isprint (optopt)) 
                        fprintf (stderr, "Unknown option `-%c'./n", optopt); 
                    else 
                        fprintf (stderr, "Unknown option character `//x%x'./n", optopt); 
                        return 1; 
                default: 
                    printf("Unknown option characte"); 
                    abort (); 
            } 
        } 
    } 
 
需要注意的是:
变量optind, optopt, opterr, optarg 都是全局变量, 外部引用, 定义时都需要加"extern"
"f:e:a"表示-f和-e有参数, -a没有参数, 编译为test,并测试
    # ./test -a 'abc' -f "abc" -e 'abc' 
    a (null) 
    f abc  
    e abc 
    # ./test -a 'abc' -f "abc" -e  
    a (null) 
    f abc  
    Option -e requires an argument. 

不过, 这样的代码还在存在问题,假如" -f"后面缺少参数, 它会误把"-e"当作"-f"的参数
    # ./test -a 'abc' -f  -e  "abc" 
    a (null) 
    f -e   wqDHTML5中文学习网 - HTML5先行者学习网

本文链接http://www.cxybl.com/html/net/winform/20120610/29307.html
wqDHTML5中文学习网 - HTML5先行者学习网
wqDHTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助