linux 中解析命令行参数 (getopt_long用法)

来源:互联网 发布:涤纶网络丝的规格 编辑:程序博客网 时间:2024/05/21 10:10
  1. #include <stdio.h>  
  2. #include <getopt.h>  
  3. char *l_opt_arg;  
  4. charconst short_options = "nbl:";  
  5. struct option long_options[] = {  
  6.      { "name",     0,   NULL,    'n'     },  
  7.      { "bf_name",  0,   NULL,    'b'     },  
  8.      { "love",     1,   NULL,    'l'     },  
  9.      {      0,     0,     0,     0},  
  10. };  
  11. int main(int argc, char *argv[])  
  12. {  
  13.      int c;  
  14.      while((c = getopt_long (argc, argv, short_options, long_options, NULL)) != -1)  
  15.      {  
  16.          switch (c)  
  17.          {  
  18.          case 'n':  
  19.              printf("My name is XL./n");  
  20.              break;  
  21.          case 'b':  
  22.              printf("His name is ST./n");  
  23.              break;  
  24.          case 'l':  
  25.              l_opt_arg = optarg;  
  26.              printf("Our love is %s!/n", l_opt_arg);  
  27.              break;  
  28.          }  
  29.      }  
  30.      return 0;  

 

 

 

[root@localhost liuxltest]# gcc -o getopt getopt.c

[root@localhost liuxltest]# ./getopt -n -b -l forever
My name is XL.
His name is ST.
Our love is forever!
[root@localhost liuxltest]#

[root@localhost liuxltest]# ./getopt -nb -l forever
My name is XL.
His name is ST.
Our love is forever!
[root@localhost liuxltest]# ./getopt -nbl forever 
My name is XL.
His name is ST.
Our love is forever!