linux中getopt的用法


getopt被用來解析命令行選項參數。就不用自己寫東東處理argv了。

#include <unistd.h>
       extern char *optarg;   //選項的參數指針
       extern int optind,    //下一次調用getopt的時,從optind存儲的位置處重新開始檢查選項。 
       extern int opterr,   //當opterr=0時,getopt不向stderr輸出錯誤信息。
       extern int optopt;   //當命令行選項字符不包括在optstring中或者選項缺少必要的參數時,該選項存儲在optopt中,getopt返回'?’、

       int getopt(int argc, char * const argv[], const char *optstring);
調用一次,返回一個選項。 在命令行選項參數再也檢查不到optstring中包含的選項時,返回-1,同時optind儲存第一個不包含選項的命令行參數。

首先說一下什么是選項,什么是參數。

字符串optstring可以下列元素,
1.單個字符,表示選項,
2.單個字符后接一個冒號:表示該選項后必須跟一個參數。參數緊跟在選項后或者以空格隔開。該參數的指針賦給optarg。
3 單個字符后跟兩個冒號,表示該選項后必須跟一個參數。參數必須緊跟在選項后不能以空格隔開。該參數的指針賦給optarg。(這個特性是GNU的擴張)。

getopt處理以'-’開頭的命令行參數,如optstring="ab:c::d::",命令行為getopt.exe -a -b host -ckeke -d haha 
在這個命令行參數中,-a和-h就是選項元素,去掉'-',a,b,c就是選項。host是b的參數,keke是c的參數。但haha並不是d的參數,因為它們中間有空格隔開。

還要注意的是默認情況下getopt會重新排列命令行參數的順序,所以到最后所有不包含選項的命令行參數都排到最后。
如getopt.exe -a ima -b host -ckeke -d haha, 都最后命令行參數的順序是: -a -b host -ckeke -d ima haha
如果optstring中的字符串以'+'加號開頭或者環境變量POSIXLY_CORRE被設置。那么一遇到不包含選項的命令行參數,getopt就會停止,返回-1。

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

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

    opterr = 0; //使getopt不行stderr輸出錯誤信息

    while( (result = getopt(argc, argv, "ab:c::")) != -1 )
    {
           switch(result)
          {
              case 'a':
                  printf("option=a, optopt=%c, optarg=%s\n", optopt, optarg);
                  break;
              case 'b':
                   printf("option=b, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case 'c':
                  printf("option=c, optopt=%c, optarg=%s\n", optopt, optarg);
                    break;
              case '?':
                    printf("result=?, optopt=%c, optarg=%s\n", optopt, optarg);
                    break;
            default:
                  printf("default, result=%c\n",result);
                  break;
          }
       printf("argv[%d]=%s\n", optind, argv[optind]);
    }
    printf("result=-1, optind=%d\n", optind);   //看看最后optind的位置

    for(result = optind; result < argc; result++)
         printf("-----argv[%d]=%s\n", result, argv[result]);

//看看最后的命令行參數,看順序是否改變了哈。
    for(result = 1; result < argc; result++)
         printf("\nat the end-----argv[%d]=%s\n", result, argv[result]);
    return 0;
}

unistd里有個 optind 變量,每次getopt后,這個索引指向argv里當前分析的字符串的下一個索引,因此
argv[optind]就能得到下個字符串,通過判斷是否以 '-'開頭就可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM