linux環境有關編程(1)

來源:互聯網
上載者:User

getopt(分析命令列參數)

   #include<unistd.h>

   int getopt(int argc,char * const argv[ ],const char * optstring);

  extern char *optarg;

  extern int optind, opterr, optopt;

  函數說明 getopt()用來分析命令列參數。

       參數argc和argv是由main()傳遞的參數個數和內容。

       參數 optstring為選項字串, 告知 getopt()可以處理哪個選項以及哪個選項需要參數。

       如果選項字串裡的字母后接著冒號“:”,則表示還有相關的參數,全域變數optarg 即會指向此額外參數。

       如果在處理期間遇到了不符合optstring指定的其他選項getopt()將顯示一個錯誤訊息,並將全域變數optarg設為“?”字元。

      如果不希望getopt()印出錯資訊,則只要將全域變數opterr設為0即可。

  getopt() 所設定的全域變數包括:

  optarg——指向當前選項參數(如果有)的指標。 optind——再次調用 getopt() 時的下一個 argv 指標的索引。 optopt——最後一個已知選項。

#include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(int argc,char *argv[]){int opt;while((opt = getopt(argc,argv,":if:lr")) != -1){switch(opt){case 'i':case 'l':case 'r':printf("option : %c \n",opt);break;case 'f':printf("filename : %s\n",optarg);break;case ':':printf("option needs a value\n");break;case '?':printf("Unknow option : %c\n",optopt);break;}}for(;optind < argc;optind++){printf("Argument: %s\n",argv[optind]);}exit(0);}

./args -i -lr 'hi there ' -f fred.c -q

option:i

option: l

option:r

filename: fred.c

unknow option:q

argument: hi there

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.