天天看點

getopt()函數解析指令行選項參數

#include <unistd.h>
    
    extern char *optarg;//目前選項的參數指針
    extern int optind;//下次再次調用getopt時,從optind存儲的位置重新可是檢查選項
    
    extern int opterr;//當opterr = 0時,getopt不向stderr輸出錯誤資訊.
    extern int optopt;//當指令行選項字元不包括在optstring中或者選項缺少必要的參數時,該選項存儲在optopt中,getopt傳回.
           

主要是介紹optarg與optind

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

使用以上函數得到檔案test.c

/*test.c*/
#include <stdio.h>
#include <unistd.h>

int main(int argc,char **argv)
{
        int ch = 0, i = 0;
        while((ch = getopt(argc,argv,"ab:c:de::"))!=-1)
        {
                printf("----------\n");
                printf("ch = %c\n",ch);
                printf("optind:%d\n",optind);
                printf("optarg=%s\n",optarg);
                printf("----------\n");
        }

        printf("::::::optind = %d\n",optind);
        for(i = 0;i<optind;i++)
        {
                printf("argv[%d] = %s)\n",i,argv[i]);
        }
        printf("\n");
        for(i = optind;i<argc;i++)
        {
                printf("argv[%d] = %s)\n",i,argv[i]);
        }
        return 0;
}

           

“ab:c:de::” b:說明選項-b後有參數,c:說明選項-c後有參數,e::說明-e與參數之間沒有空格。

a與d後面既沒有:也沒有::說明是這兩個選項的後面是不應該有參數的。

getopt()函數解析指令行選項參數

當我按照每個選項後都加入參數(這麼做當然是錯誤的)後發現,argv中發生了排序。

那些不應該有參數的選項(例如-a -d)和參數形式錯誤的參數(例如 -e的參數應該是-eee 但是我中間加入了空格變成了-e ee)以及錯誤的參數(./test 後的111)後的參數位置都發生了改變。都按照一定的順序排到了最後.而第一個排到///最後的那個坐标由while()循環結束後的optind中儲存。

這樣由于使用者輸入錯誤導緻的選項與參數順序問題就解決了

繼續閱讀