2014-07-04 43 views
0

尝试解析命令行参数,然后将其打印出来......我怎样才能使用getopt来做到这一点?通过在getopt中解析命令行参数C

我需要getopt作为后续开发代码的基础。

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

int main (int argc, char **argv) 
{ 
    char *cvalue = NULL; 
    int c; 

    while ((c = getopt (argc, argv, "n1n2n3n4c:")) != -1)    
     switch (c): 
      case n1: 
      case n2: 
      case n3: 
      case n4: 
       for(int i=0; i<argc;i++) 
       { 
        printf("Option: d%", argv[i]); 
       } 
      default: break; 


    printf ("n1flag = %d, n2flag = %d, n3flag = %d, n4flag = %d cvalue = %s\n", 
       n1flag, n2flag, n3flag, n4flag, cvalue); 

    for (index = optind; index < argc; index++) 
     printf ("Non-option argument %s\n", argv[index]); 

    return 0; 
} 
+1

您还可以看看[GNU C库(http://www.gnu.org/software/libc/manual/html_node/Getopt.html) 。 – pzaenger

+0

作为Brian的答案的附录,如果您需要-nX选项,您将使用一个需要参数的-n选项,并验证您收到的参数(例如,当您的选项为'n'时,optarg为“5”,但-n5无效)。否则,请考虑使用getopt_long_only - 为X Window系统所需样式中的选项创建的GNU函数(例如,“-display:X.Y”将作为-display选项,并且:X.Y将作为选项参数)。如果这仍然不适合你,也许你可以创建自己的参数解析器。 –

回答

1

getopt的使用单个字符作为选项,你不能因此而定义N1,N2,N3,N4,等你,而不是需要给他们,而不是独特的单字符。

请参阅getopt的手册页:http://linux.die.net/man/3/getopt