• <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++博客 :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

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

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

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

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

            或者

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

             

            如果有一個(gè)解析CDR的程序,名叫destroy,負(fù)責(zé)將一個(gè)二進(jìn)制格式的CDR文件轉(zhuǎn)換為文本文件,輸出的文本的樣式由另外一個(gè)描述文件定義,那么,命令行要求輸入的參數(shù)就有三個(gè):CDR文件名、輸出文件名和描述文件名。其中,前兩個(gè)參數(shù)是必須輸入的,第三個(gè)的描述文件名可以不輸入,程序會(huì)自動(dòng)采用默認(rèn)的輸出樣式。很自然,主函數(shù)的三個(gè)參數(shù)就應(yīng)該這樣排列:

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

             

            這樣做在一般情況下不會(huì)有太大問題,問題來源于擴(kuò)展性的需求。如果有一天,用戶要求解析程序能夠按關(guān)鍵字解析,只有含有關(guān)鍵字的CDR才能夠輸出。解決方法很簡(jiǎn)單,只要在參數(shù)列表的最后,加上它就可以了。不過,這樣就使得原本可選的描述文件名變?yōu)楸仨気斎耄?/p>

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

             

            因?yàn)椴桓牡脑挘憔筒恢溃谌齻€(gè)參數(shù)究竟是描述文件名,還是關(guān)鍵字。現(xiàn)在還算好辦,如果以后陸續(xù)有增加參數(shù)的需求,關(guān)鍵字也變成必須輸入了,這個(gè)時(shí)候,如果要查找全部CDR,你還得定義一個(gè)“特殊的關(guān)鍵字”,告訴程序,把數(shù)據(jù)統(tǒng)統(tǒng)給我撈出來……

             

            有鑒于此,在Unix/Linux的正式的項(xiàng)目上,程序員通常會(huì)使用getopt()或者getopt_long()來獲得輸入的參數(shù)。兩者的一個(gè)區(qū)別在于getopt()只支持短格式參數(shù),而getopt_long()既支持短格式參數(shù),又支持長(zhǎng)格式參數(shù)。

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

            長(zhǎng)格式:./destroy --file cdr --output cdr.txt --config cdr.desc --keyword 123456

             

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


            #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;
            }



            另外一個(gè)區(qū)別是,getopt()幾乎通用于所有類Unix系統(tǒng),而getopt_long()只有在GNU的Unix/Linux下才能用。如果把上述程序放到Tru64上編譯,就會(huì)出現(xiàn)以下錯(cuò)誤:

            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上做到長(zhǎng)格式的效果,除了自己另起爐灶之外,基本上只好借助一些跨平臺(tái)的開源項(xiàng)目了。附件里的getopt_long.c和getopt.h是從opensolaris的網(wǎng)站上抄下來的,是包含在sg3_utils軟件包中的程序。sg3_utils具體是什么,我也不知道,據(jù)說是一個(gè)Linux的開發(fā)包,用來直接使用SCSI命令集訪問設(shè)備。(sg3_utils is a package of utilities for accessing devices that use SCSI command sets.)反正拿來能用就是了!


            點(diǎn)擊下載getopt_long

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

            #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

            前兩個(gè)長(zhǎng)格式,后兩個(gè)短格式

            -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

            漏掉一個(gè)必須輸入的參數(shù)會(huì)報(bào)錯(cuò)

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

            Error: file name must be specified

            次序隨意,長(zhǎng)短混用

            -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”有什么區(qū)別,是面試C程序員經(jīng)常問到的一個(gè)問題。答案大家都知道了,#include <filename.h>,編譯器從標(biāo)準(zhǔn)庫(kù)路徑搜索filename.h,而#include “filename.h”,編譯器從用戶的工作路徑搜索filename.h。

             

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

             

            在這個(gè)小實(shí)驗(yàn)的過程中,還發(fā)現(xiàn)了C語言在各個(gè)OS下的一些細(xì)小差異,比如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);


             

            如果不設(shè)置空指針的默認(rèn)值,Linux和Tru64都會(huì)自動(dòng)幫你轉(zhuǎn)換而避免運(yùn)行時(shí)錯(cuò)誤,但是SunOS不會(huì),它會(huì)死給你看。

            ./destroy -f aaa -o aaa.txt

            Segmentation Fault (core dumped)

             

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

            warning: incompatible implicit declaration of built-in function abort

             

            由此看來,雖然C也公認(rèn)是可移植性比較好的語言,但是在跨平臺(tái)的項(xiàng)目中,也應(yīng)該注意這些微小的差別。


            本文來自CSDN博客,轉(zhuǎn)載請(qǐng)標(biāo)明出處:http://blog.csdn.net/yui/archive/2010/06/13/5669922.aspx

            麻豆亚洲AV永久无码精品久久| 亚洲精品第一综合99久久| 久久频这里精品99香蕉久| 久久国产精品波多野结衣AV| 久久亚洲国产中v天仙www| 久久精品亚洲中文字幕无码麻豆| 少妇人妻综合久久中文字幕| 亚洲午夜精品久久久久久app| 久久精品成人| 日日狠狠久久偷偷色综合96蜜桃| 久久久网中文字幕| 日韩精品无码久久一区二区三| 精品久久久久一区二区三区| 狠狠人妻久久久久久综合蜜桃| 国产精品久久久天天影视香蕉| 国产高清国内精品福利99久久| 国产精品免费久久久久影院| 九九久久精品无码专区| 久久综合久久鬼色| 久久99久久99精品免视看动漫| 亚洲中文久久精品无码ww16 | 欧美粉嫩小泬久久久久久久 | 精品久久久久久中文字幕| 久久久久夜夜夜精品国产| 韩国三级中文字幕hd久久精品| 久久伊人亚洲AV无码网站| 狠狠色狠狠色综合久久| 国产精品国色综合久久| 久久99精品久久久久久野外 | 天天爽天天狠久久久综合麻豆| 日韩精品久久久肉伦网站| 2021久久精品国产99国产精品 | 狠狠人妻久久久久久综合| 伊人久久大香线蕉AV一区二区| 亚洲va久久久噜噜噜久久天堂| 久久免费高清视频| 中文字幕无码久久精品青草| 久久久精品人妻一区二区三区蜜桃 | 国产精品久久影院| 久久影院午夜理论片无码 | 国产高潮国产高潮久久久91|