Chinaunix首页 | 论坛 | 博客
  • 博客访问: 582468
  • 博文数量: 353
  • 博客积分: 1104
  • 博客等级: 少尉
  • 技术积分: 1457
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-23 23:02
个人简介

1、刚工作时做Linux 流控;后来做安全操作系统;再后来做操作系统加固;现在做TCP 加速。唉!没离开过类Unix!!!但是水平有限。。

文章存档

2015年(80)

2013年(4)

2012年(90)

2011年(177)

2010年(1)

2009年(1)

分类:

2012-06-09 19:40:08

就下面四个API
  1. #include <stdarg.h>
  2. type va_arg(va_list ap, type);
  3. void va_copy(va_list dest, va_list src);
  4. void va_end(va_list ap);
  5. void va_start(va_list ap, argN);

代码示例一、
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdarg.h>

  4. int demo( char, ... );/*函数原型声明,至少需要一个确定的参数,注意括号内的省略号*/

  5. void main( void )
  6. {
  7.     demo("DEMO", "This", "is", "a", "demo!", "");
  8. }

  9. /*ANSI标准形式的声明方式,括号内的省略号表示可选参数*/
  10. int demo( char msg, ... )
  11. {
  12.     va_list argp;               /*第一步:定义保存函数参数的结构*/
  13.     int argno = 0;
  14.     char para;

  15.     va_start( argp, msg );      /*第二步:argp指向传入的第一个可选参数,msg是最后一个确定的参数*/
  16.     while (1){
  17.         para = va_arg( argp, char); /*第三步:指向取出形参,后面的char为参数的类型*/
  18.         if(strcmp( para, "") == 0 )
  19.             break;
  20.         printf("Parameter #%d is: %s\n", argno, para);
  21.         argno++;
  22.    }
  23.    va_end( argp );               /*第四步:将argp置为NULL*/
  24.    return 0;
  25. }

代码示例二、
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <stdarg.h>

  5. void test_1(int num, char *fmt, ...)
  6. {
  7.     printf("the string passed: %s\n",fmt);
  8.     va_list ap;

  9.     va_start(ap,fmt);

  10.     char buf[100];
  11.     vsnprintf(buf,sizeof(buf),fmt,ap);    //vsprintf(buf,fmt,ap);
  12.     printf("%s",buf);

  13.     va_end(ap);
  14. }

  15. void test_2(int num, char *fmt, ...)
  16. {
  17.     printf("the string passed: %s\n",fmt);
  18.     va_list ap;
  19.     char *name;
  20.     int age;
  21.     char *hometown;

  22.     va_start(ap,fmt);

  23.     name = va_arg(ap, char *);
  24.     printf("%s\n",name);
  25.     age = va_arg(ap, int);
  26.     printf("%d\n",age);
  27.     hometown = va_arg(ap, char *);
  28.     printf("%s\n",hometown);

  29.     va_end(ap);
  30. }

  31. void test_3(int num , char *fmt, ...)
  32. {
  33.     va_list ap;
  34.     va_start(ap,fmt);
  35.     vprintf(fmt,ap);    //vfprintf(stdout,fmt,ap);
  36.     va_end(ap);
  37. }

  38. int main(void)
  39. {
  40.     char *name = "leon";
  41.     int age = 26;
  42.     char *hometown = "Hebei";
  43.     test_3(1, "name:%s age:%d hometown:%s\n",name,age,hometown);
  44.     return 0;
  45. }

阅读(271) | 评论(0) | 转发(0) |
0

上一篇:gdb相关

下一篇:shell数组操作

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