天天看點

getopt函數的使用

http://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html#Using-Getopt

頭檔案 unistd.h

導出四個全局變量及其含義:

int opterr;

如果該變量被設定為非零值,則當getopt函數遇到未知的選項或者缺少必須的參數時,getopt函數将列印錯誤資訊到标準錯誤中。這是預設的行為。如果你将這個變量設定為零,getopt函數将不會輸出任何資訊,但是函數傳回'?'字元來表明錯誤發生。

int optopt;

當getopt函數遇到未知的選項或者缺少必須的參數時,函數将選項字元存在optopt變量中。你可以通過此方法來提供自己的錯誤提示。

int optind;

該變量被getopt函數設定為下一個将被處理的argv數組元素的下标。一旦getopt函數找到所有的選項參數,我們可以使用該變量來擷取剩餘非選項的參數的開始下标。該變量的初始值為1.

char *optarg;

該變量被getopt函數設定為指向選項的參數,即選項後面跟的參數。

函數原型

int getopt(int argc, char *const *argv, cont char *options)

getopt函數功能為從參數清單argv中獲得下一個選項參數。

參數option是一個字元串,指明符合程式要求的選項字元。一個選項字元後跟着一個冒号(如”a:“)代表該選項需要一個參數。選項字元後跟着兩個冒号(如”::“)代表該選項的參數可選。

getopt函數有三種方法處理位于非選項參數後面的選項。特殊參數”--“強制停止選項掃描。

1、預設處理方式為重新排列參數,将非選項參數移到參數末尾。這樣允許按任意順序給出函數參數。

2、

3、

getopt函數傳回選項字元。當沒有選項參數時,函數傳回-1.可能還有剩餘的非選項參數,我們可以通過比較optind和argc來确定。

如果選項帶有參數,這getopt函數通過optarg變量傳遞。

簡單的例子:

#include <ctype.h>

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

int main (int argc, char **argv)

{

int aflag = 0;

int bflag = 0;

char *cvalue = NULL;

int index;

int c;

printf("Before getopt: \n");

for(index = 0; index < argc; index++)

{

printf("argv[%d] = %s\n", index, argv[index]);

}

opterr = 1;

while ((c = getopt (argc, argv, "abc:")) != -1)

switch (c)

{

           case 'a':

             aflag = 1;

             break;

           case 'b':

             bflag = 1;

             break;

           case 'c':

             cvalue = optarg;

             break;

           case '?':

             if (optopt == 'c')

               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:

             abort ();

}

printf("After getopt: \n");

for(index = 0; index < argc; index++)

{

printf("argv[%d] = %s\n", index, argv[index]);

}

     printf ("aflag = %d, bflag = %d, cvalue = %s\n",

               aflag, bflag, cvalue);

 for (index = optind; index < argc; index++)

         printf ("Non-option argument %s\n", argv[index]);

 return 0;

}