Windows Linux可兼容版变长参数的实例程序

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

采用了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. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北雨南萍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值