2017-04-21 27 views
0

下面的C代碼工作正常,但我怎麼知道用戶是否已通過選項-d或不?如何知道特定的optarg選項是否通過c

從下面的代碼,我就能知道,只有當用戶使用OPTARG -d選項

Eg : ./application -d 

才把此代碼的工作!

如果用戶輸入

 ./application -a 

然後,我不知道,如果-d選項通過與否。

而且選項-a應該採取多個值,但下面的代碼只對單次價值

eg : ./application -a knn , lr , ln 

我怎樣才能使這個代碼接受相同的選項多個值嗎?

下面的代碼工作正常單值

eg : ./application -a knn 




     int main(int argc, char *argv[]) { 
     int opt= 0; 
     int start = -1, end = -1; 
     char *alg,*dir,*graph; 
     //Specifying the expected options 
     //The two options s and e expect numbers as argument 
     static struct option long_options[] = { 
     {"start",no_argument,0,'s' }, 
     {"end",no_argument,0,'e' }, 
     {"algorithm",no_argument, 0,'a' }, 
     {"directory",required_argument, 0,'d' }, 
     {"graph",required_argument,0,'g' }, 
     {0,0,0,0} 
     }; 

     int long_index =0; 
     int i=0,j=0; 
     size_t size = 1; 
     while ((opt = getopt_long(argc, argv,"s:e:a:d:h:g:", 
       long_options, &long_index)) != -1) { 
      switch (opt) { 
      case 'd' : 
        dir = optarg; 

         if (optarg == NULL) 
         printf("d option is must"); 
         else 
         { 
         printf("option -d value is must\n"); 
         usage(); 
         exit(EXIT_FAILURE); 
         } 
         break; 
      case '?': 
        if (optopt == ('d' || 'a' || 'g' || 's' || 'e')) 
         fprintf (stderr, "Option -%c reqd", optopt); 
         usage(); 
         exit(EXIT_FAILURE); 
      case 'a' : 
         alg = optarg; 
         if(alg == "lr" || alg == "knn" || alg == "cart") 
          { 
         printf("you entered option -a \"%s\"\n",optarg); 
          } 
         else 
          { 
         printf("Wrong option -a value is passed\n"); 
          : 
          : 
          : 

回答

0

記住,主)的參數(包括:

int main(int argc, char *argv[]) 

因此檢查argc是大於1表明,一些參數傳遞。

argv[]是指針可以遍歷該列表

#include <stdio.h> // fprintf() 
#include <stdlib.h> // exit(), EXIT_FAILURE 

int main(int argc, char *argv[]) 
{ 
    if(1 >= argc) 
    { 
     fprintf(stderr, "USAGE: %s <-d>\n", argv[0]); 
     exit(EXIT_FAILURE); 
    } 

    int found = 0; 
    for(int i = 1; i<=argc; i++) 
    { 
     if(0 == strnlen(argv[i], "-d", 2)) 
     { 
      printf("-d parameter entered\n"); 
      found = 1; 
      break; 
     } 
    } 

    if(0 == found) 
    { 
     fprintf(stderr, "some parameters entered but none are [-d\]n"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, parameter -d entered by user 

    .... 
} // end function: main 
+0

如果(0 == strnlen(argv的[I]中, 「-d」,2)),你能解釋這種燒焦字符串,以便列表代碼行? – programmer

+0

@programmer,'strlen()'的手冊頁有一個非常好的解釋,但是,爲了簡單起見,比較'argv [i]'指向的char數組的前2個字節與字符串「-d」如果它們匹配,則輸入'if()'的主體 – user3629249

相關問題