Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7791404
  • 博文数量: 701
  • 博客积分: 2150
  • 博客等级: 上尉
  • 技术积分: 13233
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-29 16:28
个人简介

天行健,君子以自强不息!

文章分类

全部博文(701)

文章存档

2019年(2)

2018年(12)

2017年(76)

2016年(120)

2015年(178)

2014年(129)

2013年(123)

2012年(61)

分类: C/C++

2013-03-06 10:11:26

命令行参数解析
linux下写服务端程序免不了用到命令行参数,这里我总结下C语言、bash脚本、pythongo语言中的使用方法,也方便我以后查阅。这里我主要用的是getopt这个函数,首先看看c语言中的定义。

头文件:#include
函数定义:
int getopt(int argc,char * const argv[ ],const char * optstring);

   extern char *optarg;

   extern int optind, opterr, optopt;

说明:

getopt函数是用来分析命令行参数的,参数argcargv是由main()传递的参数个数和内容,参数 optstring为选项字符串, 告知 getopt()可以处理哪个选项以及哪个选项需要参数。

optstring中的指定的内容的意义(例如getopt(argc, argv, "ab:c:de::")

  • 单个字符,表示选项,(如上例中的abcde各为一个选项)

  • 单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。(如上例中的b:c:

  • 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg(如上例中的e::)

 

getopt函数所设置的全局变量如下:

  • optarg : 指向当前选项参数(如果有)的指针

  • optind : 再次调用 getopt() 时的下一个 argv 指针的索引。

  • opterr : 是否打印出错信息,如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可。

  • optopt : 最后一个已知选项。

当然,在下面的例子中我也用到了getopt_long这个函数,这个和getopt类似,就不再赘述了。不懂的google下。

1c语言实现

1.1 getopt短命令

代码如下:

/* File      : getoptShort.c
        Author    : Mike
        E-Mail    : Mike_Zhang@live.com */ 
#include  
#include  
#include <string.h> 
extern char *optarg; 
extern int opterr; 
int main(int argc,char **argv)
{ 
 int c,index; 
 char host[128] = "127.0.0.1"
 int port = 8000;
 opterr = 0
 while((c=getopt(argc,argv,"h:p:")) != -1)
  { 
 switch(c)
    { 
 case 'h':
      strcpy(host,optarg); 
 break
 case 'p':
      port = atoi(optarg); 
 break
 case '?':
      printf("Usage : \n" "-h host : set ip address\n" "-p port : set port\n" ); return 1; default: break;
    }
  }

  printf( "ip   : %s\n" "port : %d\n", host,port); 
 for(index = optind;index < argc;index++)
    printf("Non-option argument %s\n",argv[index]); 
return 0;
}

 运行效果如下:

1.2 getopt长命令

这个要用到getopt_long这个函数。

代码如下:

/* File      : getoptLong.c
   Author    : Mike
   E-Mail    : Mike_Zhang@live.com */ 
#include  
#include <string.h> 
#include  
extern char *optarg; 
extern int opterr; 
int main(int argc,char **argv)
{ 
 int c,index; 
 char host[128] = "127.0.0.1"
 int port = 8000
 struct option opts[] = {
        {"host",required_argument,NULL,'h'},
        {"port",required_argument,NULL,'p'},
        {0,0,0,0}
        };

  opterr = 0
 while((c=getopt_long(argc,argv,"h:p:",opts,NULL)) != -1)
  { 
 switch(c)
    { 
 case 'h':
      strcpy(host,optarg); 
 break
 case 'p':
      port = atoi(optarg); 
 break
 case '?':
      printf("Usage : \n" "-h host : set ip address\n" "-p port : set port\n" ); 
 return 1
 default
 break;
    }
  }
  printf( "ip   : %s\n" "port : %d\n",host,port); 
 
 for(index = optind;index < argc;index++)
    printf("Non-option argument %s\n",argv[index]); 
 
 return 0;
}

 运行效果如下:

1.3 优化示例程序


  1. /******************************************************************************
  2.  * \File
  3.  * main.c
  4.  * \Brief
  5.  *
  6.  * \Author
  7.  * Hank
  8.  * \Created date
  9.  * 2013-03-12
  10.  ******************************************************************************
  11.  */
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <getopt.h>

  16. extern char *optarg;
  17. extern int opterr;
  18. struct option opts[] = {
  19.   {"ip", required_argument, NULL, 'i'},
  20.   {"port", required_argument, NULL, 'p'},
  21.   {"host", required_argument, NULL, 's'},
  22.   {"out" , required_argument, NULL, 'o'},
  23.   {"help", required_argument, NULL, 'h'},
  24.   {0,0,0,0}
  25. };

  26. int parse_params(int argc, char** argv, char* ip, int* port, char* host, char* f);

  27. int main(int argc, char* argv[])
  28. {
  29.   char ip[32] = "225.1.1.31";
  30.   int port = 1234;
  31.   char host[32] = "127.0.0.1";
  32.   char filename[512] = "udp.dat";

  33.   /*Parsing command-line parameters */
  34.   parse_params(argc, argv, ip, &port, host, filename);
  35.                                                                                          
  36.                                                                                          
  37.   return 0;
  38. } int parse_params(int argc, char** argv,
  39.       char* ip, int* port, char* host, char* f)
  40. {
  41.   int c, index;

  42.   opterr = 0;
  43.   while ((c = getopt_long(argc, argv, "i:p:s:o:h", opts, NULL)) != -1)
  44.   {
  45.     switch (c)
  46.     {
  47.       case 'i':
  48.         strcpy(ip, optarg);
  49.         break;
  50.       case 'p':
  51.         *port = atoi(optarg);
  52.         break;
  53.       case 's':
  54.         strcpy(host, optarg);
  55.         break;
  56.       case 'o':
  57.         strcpy(f, optarg);
  58.         break;
  59.       case 'h':
  60.       default:
  61.         printf("Usage: \n");
  62.         printf("-i ip : set udp's ip address\n");
  63.         printf("-p port : set udp's port\n");
  64.         printf("-s host : set local addresss\n");
  65.         printf("-o file : set output filename\n");
  66.         printf("-h : print help information\n");
  67.         return 1;
  68.       }
  69.   }
  70.                                                                                                                                                                
  71.   /* show banner */
  72.   printf("ip : %s \nport : %d \nhost : %s \nfile : %s\n",
  73.         ip, *port, host, f);
  74.                                                                                                                                                                
  75.   for (index = optind; index < argc; index++)
  76.     printf("Non-option argument %s\n", argv[index]);
  77.                                                                                                                                                                
  78.   return 0;
  79. }
2Bash脚本实现

bash的和c语言的类似,这里只列举一个短命令的示例。

代码如下:

View Code

3.python实现

python里面的这个函数显然已经进化了,这个更简单,还是那个程序的功能,代码如下:

#! /usr/bin/python 
import getopt,sys 
if __name__ == "__main__"
try:
  opts,args = getopt.getopt(sys.argv[1:],"h:p:",["host=","port="])
 except getopt.GetoptError: 
 print "Usage :" 
 print "-h arg , --host=arg : set ip address" 
 print "-p arg , --port=arg : set port" 
 sys.exit(1)
  host = "127.0.0.1" 
 port = 8000 
 for opt,arg in opts: 
 if opt in ("-h","--host"):
       host = arg if opt in ("-p","--port"):
       port = arg print "ip   : ",host print "port : ",port

 4.go语言实现

go语言的flag库似乎更全面,下面是代码:

package main 
import (  "flag"  "fmt" ) 
var (  ip = flag.String("host","127.0.0.1","ip address")  
 port = flag.String("port","8000","listen port") ) 
func main() {  
 flag.Parse()  
 fmt.Println("ip   : ",*ip)  
 fmt.Println("port : ",*port) 
}
原文链接:
http://www.cnblogs.com/MikeZhang/archive/2012/09/07/argsTest20120907.html 
阅读(1331) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~