Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1896311
  • 博文数量: 152
  • 博客积分: 3730
  • 博客等级: 上尉
  • 技术积分: 3710
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-02 14:36
个人简介

减肥,运动,学习,进步...

文章分类

全部博文(152)

文章存档

2016年(14)

2015年(17)

2014年(16)

2013年(4)

2012年(66)

2011年(35)

分类: C/C++

2016-08-02 19:47:10

在编写C语言代码的过程中经常会使用printf实现打印的格式化,该函数支持多样化的参数,同时还支持不定个数的参数,即可变参数。有关可变参数都知道是采用了va_list实现。通常是采用如下的形式:
va_list vp;
va_start(vp, arg1);
typevalue1 = va_arg(vp, typename1);
...
typevalueN = va_arg(vp, typenameN);
va_end(vp);

以上是可变参数的使用方法,其中定义可变参数的函数必须有至少一个确定的参数。比如函数printf的声明如下所示:
int printf(const char *format, ...);
其中format是必须的参数,否则该函数将编译出错。
从上述的代码格式中可知,可以通过多次调用va_arg()获取对应的参数值,该值的获取还需要知道对应的值类型。多次调用该接口还需要有关可变参数的个数,这些信息都要通过某种形式传递到。因此使用va_list必须要知道参数的个数以及对应参数的类型等。

在通常接触到的可变参数接口printf时实际上传递了这些参数,因为调用printf()函数时通常会设定一系列的格式,而这些格式实际上就指出了当前可变参数的个数,以及对应的参数类型,这些都是通过在format中指定的,这样printf通过format中格式化的符号就能确定类型,同时转义字符的个数也就确定了可变参数的个数。如下所示:
printf("%d,%d,%d,%d\n", a, b , c, d);通过%d的数量可知,可变参数的个数为4个,%d表示整数,因此需要的类型也就对应于int。
这里简单的介绍一下va_list的实现方法:
在C语言中堆栈是一个非常重要的部分,理解了堆栈的组成才能了解程序的调用过程,这部分简单的介绍函数调用过程中的堆栈形式。基本模型如下所示:

函数调用的基本模型如下所示,其中参数可以通过当前的栈帧的位置找到对应的参数位置,即根据Calledfunc_EBP的位置就能找到调用当前函数的函数传递的参数值。而这些参数值也保存在了堆栈空间中,通过参数的占用空间大小和当前参数的保存位置就能计算出其他参数的位置。由于在va_list中必须有一个已知的确定参数,该参数实际上就是用来确定可变参数的起始位置,确定的基本原理如上图所示。当然该图只是一个模型图,具体的实现可能存在一些差异。这里不进行详细的描述。

这里简单的编写一个求可变个数整形求和的方法,其中size参数用来保存参数个数,由于是整形,va_arg直接对int型进行处理

点击(此处)折叠或打开

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>

  4. #include <stdarg.h>

  5. int f(int x, int y, int z)
  6. {
  7.     return x + y + z;
  8. }

  9. int sum(int size, ...)
  10. {
  11.     va_list vp;
  12.     int s = 0;
  13.     int i = 0;
  14.    
  15.     va_start(vp, size);
  16.     for (i = 0; i < size; ++ i) {
  17.         s += va_arg(vp, int);
  18.     }
  19.     va_end(vp);

  20.     printf("%d,%d\n", size, s);
  21. }

  22. int main()
  23. {
  24.     int a = 1;
  25.     int b = 2;
  26.     int c = 3;

  27.     printf("%d\n", f(a, b , c));
  28.     sum(5, 20, 30, 40, 50, 20);
  29.     return 0;
  30. }
  有关va_list的用法还很多,在报文解析相关的代码中存在很多处理,该例子是获取相同类型的数据,在格式化处理中可能存在各种各种的格式,只需要根据不同的格式分别获取参数就能完成复杂格式的处理。这部分可以参看redis-cli对cli的处理逻辑,如下所示:

点击(此处)折叠或打开

  1. void *redisCommand(redisContext *c, const char *format, ...) {
  2.     va_list ap;
  3.     void *reply = NULL;
  4.     va_start(ap,format); //已format作为可变参数的相对起始地址
  5.     reply = redisvCommand(c,format,ap); //对ap进行处理
  6.     va_end(ap);
  7.     return reply;
  8. }
  接下来查看ap相关的操作逻辑:

点击(此处)折叠或打开

  1. int redisvFormatCommand(char **target, const char *format, va_list ap) {
  2.     const char *c = format;
  3.     char *cmd = NULL; /* final command */
  4.     int pos; /* position in final command */
  5.     sds curarg, newarg; /* current argument */
  6.     int touched = 0; /* was the current argument touched? */
  7.     char **curargv = NULL, **newargv = NULL;
  8.     int argc = 0;
  9.     int totlen = 0;
  10.     int j;

  11.     /* Abort if there is not target to set */
  12.     if (target == NULL)
  13.         return -1;

  14.     /* Build the command string accordingly to protocol */
  15.     curarg = sdsempty();
  16.     if (curarg == NULL)
  17.         return -1;

  18.     while(*c != '\0') {
  19.         if (*c != '%' || c[1] == '\0') {
  20.             if (*c == ' ') {
  21.                 if (touched) {
  22.                     newargv = realloc(curargv,sizeof(char*)*(argc+1));
  23.                     if (newargv == NULL) goto err;
  24.                     curargv = newargv;
  25.                     curargv[argc++] = curarg;
  26.                     totlen += bulklen(sdslen(curarg));

  27.                     /* curarg is put in argv so it can be overwritten. */
  28.                     curarg = sdsempty();
  29.                     if (curarg == NULL) goto err;
  30.                     touched = 0;
  31.                 }
  32.             } else {
  33.                 newarg = sdscatlen(curarg,c,1);
  34.                 if (newarg == NULL) goto err;
  35.                 curarg = newarg;
  36.                 touched = 1;
  37.             }
  38.         } else {
  39.             char *arg;
  40.             size_t size;

  41.             /* Set newarg so it can be checked even if it is not touched. */
  42.             newarg = curarg;

  43.             switch(c[1]) {
  44.             case 's':  //字符串的处理
  45.                 arg = va_arg(ap,char*);
  46.                 size = strlen(arg);
  47.                 if (size > 0)
  48.                     newarg = sdscatlen(curarg,arg,size);
  49.                 break;
  50.             case 'b':
  51.                 arg = va_arg(ap,char*); //先获取字符串地址
  52.                 size = va_arg(ap,size_t); //获取字符串的长度
  53.                 if (size > 0)
  54.                     newarg = sdscatlen(curarg,arg,size);
  55.                 break;
  56.             case '%':
  57.                 newarg = sdscat(curarg,"%");
  58.                 break;
  59.             default:
  60.                 /* Try to detect printf format */
  61.                 {
  62.                     static const char intfmts[] = "diouxX";
  63.                     char _format[16];
  64.                     const char *_p = c+1;
  65.                     size_t _l = 0;
  66.                     va_list _cpy;

  67.                     /* Flags */
  68.                     if (*_p != '\0' && *_p == '#') _p++;
  69.                     if (*_p != '\0' && *_p == '0') _p++;
  70.                     if (*_p != '\0' && *_p == '-') _p++;
  71.                     if (*_p != '\0' && *_p == ' ') _p++;
  72.                     if (*_p != '\0' && *_p == '+') _p++;

  73.                     /* Field width */
  74.                     while (*_p != '\0' && isdigit(*_p)) _p++;

  75.                     /* Precision */
  76.                     if (*_p == '.') {
  77.                         _p++;
  78.                         while (*_p != '\0' && isdigit(*_p)) _p++;
  79.                     }

  80.                     /* Copy va_list before consuming with va_arg */
  81.                     va_copy(_cpy,ap);

  82.                     /* Integer conversion (without modifiers) */
  83.                     if (strchr(intfmts,*_p) != NULL) {
  84.                         va_arg(ap,int); //获取参数
  85.                         goto fmt_valid;
  86.                     }

  87.                     /* Double conversion (without modifiers) */
  88.                     if (strchr("eEfFgGaA",*_p) != NULL) {
  89.                         va_arg(ap,double); //获取浮点数
  90.                         goto fmt_valid;
  91.                     }

  92.                     /* Size: char */
  93.                     if (_p[0] == 'h' && _p[1] == 'h') {
  94.                         _p += 2;
  95.                         if (*_p != '\0' && strchr(intfmts,*_p) != NULL) {
  96.                             va_arg(ap,int); /* char gets promoted to int */
  97.                             goto fmt_valid;
  98.                         }
  99.                         goto fmt_invalid;
  100.                     }

  101.                     /* Size: short */
  102.                     if (_p[0] == 'h') {
  103.                         _p += 1;
  104.                         if (*_p != '\0' && strchr(intfmts,*_p) != NULL) {
  105.                             va_arg(ap,int); /* short gets promoted to int */
  106.                             goto fmt_valid;
  107.                         }
  108.                         goto fmt_invalid;
  109.                     }

  110.                     /* Size: long long */
  111.                     if (_p[0] == 'l' && _p[1] == 'l') {
  112.                         _p += 2;
  113.                         if (*_p != '\0' && strchr(intfmts,*_p) != NULL) {
  114.                             va_arg(ap,long long);
  115.                             goto fmt_valid;
  116.                         }
  117.                         goto fmt_invalid;
  118.                     }

  119.                     /* Size: long */
  120.                     if (_p[0] == 'l') {
  121.                         _p += 1;
  122.                         if (*_p != '\0' && strchr(intfmts,*_p) != NULL) {
  123.                             va_arg(ap,long);
  124.                             goto fmt_valid;
  125.                         }
  126.                         goto fmt_invalid;
  127.                     }

  128.                 fmt_invalid:
  129.                     va_end(_cpy);
  130.                     goto err;

  131.                 fmt_valid:
  132.                     _l = (_p+1)-c;
  133.                     if (_l < sizeof(_format)-2) {
  134.                         memcpy(_format,c,_l);
  135.                         _format[_l] = '\0';
  136.                         newarg = sdscatvprintf(curarg,_format,_cpy);

  137.                         /* Update current position (note: outer blocks
  138.                          * increment c twice so compensate here) */
  139.                         c = _p-1;
  140.                     }

  141.                     va_end(_cpy);
  142.                     break;
  143.                 }
  144.             }

  145.             if (newarg == NULL) goto err;
  146.             curarg = newarg;

  147.             touched = 1;
  148.             c++;
  149.         }
  150.         c++;
  151.     }

  152.     /* Add the last argument if needed */
  153.     if (touched) {
  154.         newargv = realloc(curargv,sizeof(char*)*(argc+1));
  155.         if (newargv == NULL) goto err;
  156.         curargv = newargv;
  157.         curargv[argc++] = curarg;
  158.         totlen += bulklen(sdslen(curarg));
  159.     } else {
  160.         sdsfree(curarg);
  161.     }

  162.     /* Clear curarg because it was put in curargv or was free'd. */
  163.     curarg = NULL;

  164.     /* Add bytes needed to hold multi bulk count */
  165.     totlen += 1+intlen(argc)+2;

  166.     /* Build the command at protocol level */
  167.     cmd = malloc(totlen+1);
  168.     if (cmd == NULL) goto err;

  169.     pos = sprintf(cmd,"*%d\r\n",argc);
  170.     for (j = 0; j < argc; j++) {
  171.         pos += sprintf(cmd+pos,"$%zu\r\n",sdslen(curargv[j]));
  172.         memcpy(cmd+pos,curargv[j],sdslen(curargv[j]));
  173.         pos += sdslen(curargv[j]);
  174.         sdsfree(curargv[j]);
  175.         cmd[pos++] = '\r';
  176.         cmd[pos++] = '\n';
  177.     }
  178.     assert(pos == totlen);
  179.     cmd[pos] = '\0';

  180.     free(curargv);
  181.     *target = cmd;
  182.     return totlen;

  183. err:
  184.     while(argc--)
  185.         sdsfree(curargv[argc]);
  186.     free(curargv);

  187.     if (curarg != NULL)
  188.         sdsfree(curarg);

  189.     /* No need to check cmd since it is the last statement that can fail,
  190.      * but do it anyway to be as defensive as possible. */
  191.     if (cmd != NULL)
  192.         free(cmd);

  193.     return -1;
  194. }
 从上述的代码中实际上是对va_list进行反复的操作获取具体的内容。通过va_list就能相对简单的解决格式化操作。
阅读(14331) | 评论(0) | 转发(2) |
0

上一篇:Linux守护进程的深入理解

下一篇:没有了

给主人留下些什么吧!~~