• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            The power of C, the power of MD

            A problem is a chance to do your best
            posts - 11, comments - 22, trackbacks - 0, articles - 0
              C++博客 :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

            使用getopt_long()從命令行獲取參數

            Posted on 2010-07-29 18:01 roy 閱讀(2155) 評論(0)  編輯 收藏 引用 所屬分類: C/C++

            眾所周知,C程序的主函數有兩個參數,其中,第一個參數是整型,可以獲得包括程序名字的參數個數,第二個參數是字符數組指針或字符指針的指針,可以按順序獲得命令行上各個字符串參數。其原形是:

            int main(int argc, char *argv[]);

            或者

            int main(int argc, char **argv);

             

            如果有一個解析CDR的程序,名叫destroy,負責將一個二進制格式的CDR文件轉換為文本文件,輸出的文本的樣式由另外一個描述文件定義,那么,命令行要求輸入的參數就有三個:CDR文件名、輸出文件名和描述文件名。其中,前兩個參數是必須輸入的,第三個的描述文件名可以不輸入,程序會自動采用默認的輸出樣式。很自然,主函數的三個參數就應該這樣排列:

            ./destroy cdr cdr.txt [cdr.desc]

             

            這樣做在一般情況下不會有太大問題,問題來源于擴展性的需求。如果有一天,用戶要求解析程序能夠按關鍵字解析,只有含有關鍵字的CDR才能夠輸出。解決方法很簡單,只要在參數列表的最后,加上它就可以了。不過,這樣就使得原本可選的描述文件名變為必須輸入:

            ./destroy cdr cdr.txt cdr.desc [keyword]

             

            因為不改的話,你就不知道,第三個參數究竟是描述文件名,還是關鍵字。現在還算好辦,如果以后陸續有增加參數的需求,關鍵字也變成必須輸入了,這個時候,如果要查找全部CDR,你還得定義一個“特殊的關鍵字”,告訴程序,把數據統統給我撈出來……

             

            有鑒于此,在Unix/Linux的正式的項目上,程序員通常會使用getopt()或者getopt_long()來獲得輸入的參數。兩者的一個區別在于getopt()只支持短格式參數,而getopt_long()既支持短格式參數,又支持長格式參數。

            短格式:./destroy -f cdr -o cdr.txt -c cdr.desc -k 123456

            長格式:./destroy --file cdr --output cdr.txt --config cdr.desc --keyword 123456

             

            引入了getopt()和getopt_long()的項目,設計者可以按需要,方便地增加參數,或者隨意地放置參數的先后次序,只需要在程序中判斷,哪些參數是必須的就可以了。關于這兩個函數的用法,大家可以上網搜索一下,不再累述。附件destroy_linux.c給出了在Linux下使用getopt_long()的實例。


            #include <stdio.h>
            #include 
            <stdlib.h>
            #include 
            <unistd.h>
            #include 
            <getopt.h>

            void print_usage(const char *program_name) {
                printf(
            "%s 1.0.0 (2010-06-13)\n", program_name);
                printf(
            "This is a program decoding a BER encoded CDR file\n");
                printf(
            "Usage: %s -f <file_name> -o <output_name> [-c <config_name>] [-k <keyword>]\n", program_name);
                printf(
            "    -f --file       the CDR file to be decoded\n");
                printf(
            "    -o --output     the output file in plain text format\n");
                printf(
            "    -c --config     the description file of the CDR file, if not given, use default configuration\n");
                printf(
            "    -k --keyword    the keyword to search, if not given, all records will be written into output file\n");
            }


            int main(int argc, char *argv[]) {
                
            char *file_name = NULL;
                
            char *output_name = NULL;
                
            char *config_name = NULL;
                
            char *keyword = NULL;

                
            const char *short_opts = "hf:o:c:k:";
                
            const struct option long_opts[] = {
                    
            {"help", no_argument, NULL, 'h'},
                    
            {"file", required_argument, NULL, 'f'},
                    
            {"output", required_argument, NULL, 'o'},
                    
            {"config", required_argument, NULL, 'c'},
                    
            {"keyword", required_argument, NULL, 'k'},
                    
            {0000}
                }
            ;
                
            int hflag = 0;

                
            int c;
                opterr 
            = 0;

                
            while ( (c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1 ) {
                    
            switch ( c ) {
                        
            case 'h' :
                            hflag 
            = 1;
                            
            break;
                        
            case 'f' :
                            file_name 
            = optarg;
                            
            break;
                        
            case 'o' :
                            output_name 
            = optarg;
                            
            break;
                        
            case 'c' :
                            config_name 
            = optarg;
                            
            break;
                        
            case 'k' :
                            keyword 
            = optarg;
                            
            break;
                        
            case '?' :
                            
            if ( optopt == 'f' || optopt == 'o' || optopt == 'c' || optopt == 'k' )
                                printf(
            "Error: option -%c requires an argument\n", optopt);
                            
            else if ( isprint(optopt) )
                                printf(
            "Error: unknown option '-%c'\n", optopt);
                            
            else
                                printf(
            "Error: unknown option character '\\x%x'\n", optopt);
                            
            return 1;
                        
            default :
                            abort();
                    }

                }


                
            if ( hflag || argc == 1 ) {
                    print_usage(argv[
            0]);
                    
            return 0;
                }

                
            if ( !file_name ) {
                    printf(
            "Error: file name must be specified\n");
                    
            return 1;
                }

                
            if ( !output_name ) {
                    printf(
            "Error: output name must be specified\n");
                    
            return 1;
                }


                
            // if not setting default, Linux OK, but SunOS core dump
                if ( !config_name ) config_name = "(null)";
                
            if ( !keyword ) keyword = "(null)";
                printf(
            "Parameters got: file_name = %s, output_name = %s, config_name = %s, keyword = %s\n", file_name, output_name, config_name, keyword);
                
            return 0;
            }



            另外一個區別是,getopt()幾乎通用于所有類Unix系統,而getopt_long()只有在GNU的Unix/Linux下才能用。如果把上述程序放到Tru64上編譯,就會出現以下錯誤:

            cc -o destroy destroy_linux.c

            cc: Error: destroy_linux.c, line 24: In the initializer for long_opts, an array's element type is incomplete, which precludes its initialization. (incompelinit)

                            {"help", no_argument, NULL, 'h'},

            ----------------^

             

            所以,如果一定要在Tru64等非GNU的OS上做到長格式的效果,除了自己另起爐灶之外,基本上只好借助一些跨平臺的開源項目了。附件里的getopt_long.c和getopt.h是從opensolaris的網站上抄下來的,是包含在sg3_utils軟件包中的程序。sg3_utils具體是什么,我也不知道,據說是一個Linux的開發包,用來直接使用SCSI命令集訪問設備。(sg3_utils is a package of utilities for accessing devices that use SCSI command sets.)反正拿來能用就是了!


            點擊下載getopt_long

            拿過來后,把他們放到與destroy_linux.c同一目錄下,只需要把destroy_linux.c的頭文件改一個地方,#include <getopt.h>改為#include “getopt.h”,就能夠編譯運行了。而且,這樣改好后,不僅在Tru64上能運行,在Linux、SunOS上也能運行。

            #include <stdio.h>
            #include 
            <stdlib.h>
            #include 
            <unistd.h>
            #include 
            "getopt.h"

            void print_usage(const char *program_name) {
                printf(
            "%s 1.0.0 (2010-06-13)\n", program_name);
                printf(
            "This is a program decoding a BER encoded CDR file\n");
                printf(
            "Usage: %s -f <file_name> -o <output_name> [-c <config_name>] [-k <keyword>]\n", program_name);
                printf(
            "    -f --file       the CDR file to be decoded\n");
                printf(
            "    -o --output     the output file in plain text format\n");
                printf(
            "    -c --config     the description file of the CDR file, if not given, use default configuration\n");
                printf(
            "    -k --keyword    the keyword to search, if not given, all records will be written into output file\n");
            }


            int main(int argc, char *argv[]) {
                
            char *file_name = NULL;
                
            char *output_name = NULL;
                
            char *config_name = NULL;
                
            char *keyword = NULL;

                
            const char *short_opts = "hf:o:c:k:";
                
            const struct option long_opts[] = {
                    
            {"help", no_argument, NULL, 'h'},
                    
            {"file", required_argument, NULL, 'f'},
                    
            {"output", required_argument, NULL, 'o'},
                    
            {"config", required_argument, NULL, 'c'},
                    
            {"keyword", required_argument, NULL, 'k'},
                    
            {0000}
                }
            ;
                
            int hflag = 0;

                
            int c;
                opterr 
            = 0;

                
            while ( (c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1 ) {
                    
            switch ( c ) {
                        
            case 'h' :
                            hflag 
            = 1;
                            
            break;
                        
            case 'f' :
                            file_name 
            = optarg;
                            
            break;
                        
            case 'o' :
                            output_name 
            = optarg;
                            
            break;
                        
            case 'c' :
                            config_name 
            = optarg;
                            
            break;
                        
            case 'k' :
                            keyword 
            = optarg;
                            
            break;
                        
            case '?' :
                            
            if ( optopt == 'f' || optopt == 'o' || optopt == 'c' || optopt == 'k' )
                                printf(
            "Error: option -%c requires an argument\n", optopt);
                            
            else if ( isprint(optopt) )
                                printf(
            "Error: unknown option '-%c'\n", optopt);
                            
            else
                                printf(
            "Error: unknown option character '\\x%x'\n", optopt);
                            
            return 1;
                        
            default :
                            abort();
                    }

                }


                
            if ( hflag || argc == 1 ) {
                    print_usage(argv[
            0]);
                    
            return 0;
                }

                
            if ( !file_name ) {
                    printf(
            "Error: file name must be specified\n");
                    
            return 1;
                }

                
            if ( !output_name ) {
                    printf(
            "Error: output name must be specified\n");
                    
            return 1;
                }


                
            // if not setting default, Linux OK, but SunOS core dump
                if ( !config_name ) config_name = "(null)";
                
            if ( !keyword ) keyword = "(null)";
                printf(
            "Parameters got: file_name = %s, output_name = %s, config_name = %s, keyword = %s\n", file_name, output_name, config_name, keyword);
                
            return 0;
            }



            Linux下編譯

            -bash-3.2$ gcc -o destroy destroy.c getopt_long.c

            短格式,全部輸入

            -bash-3.2$ ./destroy -f aaa -o aaa.txt -c ccc -k 222

            Parameters got: file_name = aaa, output_name = aaa.txt, config_name = ccc, keyword = 222

            前兩個長格式,后兩個短格式

            -bash-3.2$ ./destroy --file aaa --output aaa.txt -c ccc -k 222

            Parameters got: file_name = aaa, output_name = aaa.txt, config_name = ccc, keyword = 222

            漏掉一個必須輸入的參數會報錯

            -bash-3.2$ ./destroy -output aaa.txt

            Error: file name must be specified

            次序隨意,長短混用

            -bash-3.2$ ./destroy -c ccc -o aaa.txt -k 222 --file aaa

            Parameters got: file_name = aaa, output_name = aaa.txt, config_name = ccc, keyword = 222

             

            題外話,#include <filename.h>與#include “filename.h”有什么區別,是面試C程序員經常問到的一個問題。答案大家都知道了,#include <filename.h>,編譯器從標準庫路徑搜索filename.h,而#include “filename.h”,編譯器從用戶的工作路徑搜索filename.h。

             

            此外,網上也有人說從glibc(http://sourceware.org/glibc/)上把getopt.h、getopt.c和getoptl.c拿過來也能夠用。我也試過,但是不清楚什么原因不成功。

             

            在這個小實驗的過程中,還發現了C語言在各個OS下的一些細小差異,比如destroy.c里,79行到82行:

            // if not setting default, Linux OK, but SunOS core dump
            if ( !config_name ) config_name = "(null)";
            if ( !keyword ) keyword = "(null)";
            printf(
            "Parameters got: file_name = %s, output_name = %s, config_name = %s, keyword = %s\n", file_name, output_name, config_name, keyword);


             

            如果不設置空指針的默認值,Linux和Tru64都會自動幫你轉換而避免運行時錯誤,但是SunOS不會,它會死給你看。

            ./destroy -f aaa -o aaa.txt

            Segmentation Fault (core dumped)

             

            再比如,第62行的abort()在頭文件stdlib.h中定義,如果不包含此文件,SunOS與Tru64編譯都沒問題,Linux編譯時會警告:

            warning: incompatible implicit declaration of built-in function abort

             

            由此看來,雖然C也公認是可移植性比較好的語言,但是在跨平臺的項目中,也應該注意這些微小的差別。


            本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/yui/archive/2010/06/13/5669922.aspx

            中文字幕久久波多野结衣av| 亚洲国产精品无码久久| 久久精品无码一区二区三区免费 | 久久99精品国产麻豆宅宅| 久久中文骚妇内射| 国产精品青草久久久久福利99 | 91久久精品视频| 久久亚洲精品无码aⅴ大香| 国内精品久久久久影院一蜜桃| 99热成人精品免费久久| 人妻丰满AV无码久久不卡| 久久久久亚洲av成人无码电影 | 久久亚洲AV无码精品色午夜麻豆 | 久久久久久免费一区二区三区| 青青久久精品国产免费看| 波多野结衣中文字幕久久| 色99久久久久高潮综合影院| 色综合久久天天综合| 伊人久久久AV老熟妇色| 久久亚洲av无码精品浪潮| 精品久久久久久综合日本| 99精品国产综合久久久久五月天| 热久久国产精品| 精品久久久久香蕉网| 国内精品九九久久精品 | 久久99国产综合精品女同| 久久综合亚洲色一区二区三区| 国产精品亚洲美女久久久| 91久久婷婷国产综合精品青草| 久久AV高潮AV无码AV| 色诱久久av| 午夜视频久久久久一区 | 亚洲国产精品久久电影欧美| 无码人妻久久一区二区三区蜜桃| 999久久久免费国产精品播放| 欧美一区二区三区久久综合 | 久久水蜜桃亚洲av无码精品麻豆| 久久99久国产麻精品66| 久久91精品国产91久| 色8激情欧美成人久久综合电| 精品无码久久久久久国产|