2015年6月21日 星期日

[C筆記]命令列選項與命令列引數


practice

sample code:

#include <stdio.h>

#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
    char *delivery ="";
    int thick =0;
    int count =0;
    char ch;
  while( (ch =getopt(argc,argv,"d:g:t"))!=EOF)
  switch (ch){
         case 'd':
                  delivery = optarg;
                  break;
         case 'g':
                  printf("%s\n",optarg);
         case 't':
                   thick = 1;
                  break;
                 
         default:
                 fprintf(stderr,"Unknow option: '%s'\n",optarg) ;
                 return 1;    
         }  
         argc-=optind;
         argv+=optind;
       
         if(thick)
         puts("thick crust");  
         if(delivery[0])
         printf("to be delivery %s .\n",delivery);
         for(count = 0;count<argc;count++)
         puts(argv[count]);
    return 0;
}


執行結果:


要點補充說明:

getopt 使用前必須先#include<unistd.h>

利用getopt 來設置選項 d  : 代表此選項後面必須帶參數(-d now)

命令(try.exe -d now -g go -t output1 output2)

*argc為8
*argv為8 (argv[0]~argv[7])
*變數 optind為6  (output1,output2為參數所以不算命令數)
*變數 optarg 內容利用case '指令' 來區分輸入的參數( case 'd': optarg 為 -d  後面帶入的值)
*arg+=optind (將 arg[0]變成output1 arg[2]變成 output2)

沒有留言:

張貼留言