Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7793764
  • 博文数量: 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++

2012-11-05 19:27:16

自己写的一个可变长参数的例子程序。

采用了Linux Windows可兼容版本函数。

main.c

  1. /*
  2.  * This project is implemented for testing variable-argument
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>

  6. #include "log.h"

  7. FILE *fp_log = NULL;

  8. void main(char arg, char *argv[])
  9. {
  10.   if ((fp_log = fopen("test.log", "w+")) == NULL)
  11.   {
  12.     printf("The file 'test.log' was not opened\n");
  13.   }

  14.   tc_log(fp_log, "%s", __FUNCTION__);
  15.   tc_log(fp_log, "%s, %d", __FUNCTION__, 1);
  16.   tc_log(fp_log, "%s, %d, %s, %d", __FUNCTION__, 2, __FUNCTION__, 2);

  17.   if( fclose(fp_log))
  18.     printf( "The file 'test.log' was not closed\n");
  19. }
log.h

  1. /*
  2.  * File: log.h
  3.  */

  4. #ifndef __LOG_H__
  5. #define __LOG_H__
  6. #include <stdarg.h>

  7. typedef char * va_list;
  8. extern FILE *fp_log;

  9. void tc_log(const FILE *fp_log, const char *fmt, ...);
  10. void tc_log_default(const FILE *fp_log, const char * fmt, va_list vl);
  11. #endif
log.c

  1. /*
  2.  * File: log.c
  3.  */
  4. #include "stdio.h"
  5. #include "log.h"


  6. void tc_log(const FILE *fp_log, const char *fmt, ...)
  7. {
  8.   va_list vl;

  9.   /* Macro to set 'vl' to beginning of list of optional arguments */
  10.   va_start(vl, fmt);
  11.   
  12.   tc_log_default(fp_log, fmt, vl);
  13.   
  14.   /* Macro to reset arg_ptr */
  15.   va_end(vl);

  16.   return;
  17. }

  18. void tc_log_default(const FILE *fp_log, const char * fmt, va_list vl)
  19. {
  20.   char line[1024];
  21.   line[0] = 0;
  22.   printf("strlen = %d, sizeof = %d\n", strlen(line), sizeof(line));

  23.   vsnprintf(line + strlen(line), sizeof(line) - strlen(line), fmt, vl);
  24.   fprintf(fp_log, "%s\n", line);

  25.   return;
  26. }

阅读(1840) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~