2020年5月27日 星期三

getopt()的使用

至少三十年沒有用這個Call了,除了Function的大致的功能,其他都忘記了。

第一: 先要在前面加Include:

#include <unistd.h>

Call的格式如下:

int getopt (int Argc, char * const Argv[], const char *Optstring);

前面兩個參數int Argc, char * const Argv[],就是 main()由 Shell 傳進來的兩個參數。
optstring 就是這個Function的精華。

如果 "a:bcf:"。代表要接受的option有 -a, -b, -c。

其中option a的後面還有":"號,代表 -a 這個Flag的後面還有一個參數。
例如 -f filename 也是上面的四個參數的用法。

getopt()提供兩個global variable : optarg 與 optopt。用來輔助getopt()這個function。
遇到像 f: 這樣的參數,getopt()會將 -f 後面的字串放到optarg中。

考慮以下這個命令:

# cdr -a -d -f Filename.log
Usage:
-a : print all information
-c:  print non-zero information only, but only raw data (cvs format)
-d: print device_name
-f:  Filename.log

--------------------------------------------------------------------------------------

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

int main(int argc, char **argv)
{
    int ch;
    int Opt_a = 0;
    int Opt_c = 0;
    int Opt_d = 0;
    int option = 0 ;

    while ((ch=getopt(argc,argv,"acdf:"))!=-1)
    {
       switch(ch)
       {
          case 'a':
                 Opt_a = 1 ;
                 option = 1 ;
             printf("optiona a is on \n");
                 break;
          case 'c':
                 Opt_c = 1 ;
                 option = 1 ;
                 printf("optiona c is on\n");
                 break;
          case 'd':
                 Opt_d = 1 ;
                 option = 1 ;
                 printf("optiona d is on\n");
                 break;
          case 'f':
                printf("option f\n");
                option = 1 ;
                printf("Filename: %s\n",optarg);
                break;
          default:
                printf("Usage: \n") ;
                break;
        }  /* end of switch */
    } /* end of while */
}

-----------------------------------------------------------------------------------------
# cc t.c <Enter>
# ./a.out -d -f filename -a -c <Enter>
optiona d is on
option f
Filename: filename
optiona a is on
optiona c is on
#


沒有留言:

張貼留言