自己写的一个可变长参数的例子程序。
采用了Linux Windows可兼容版本函数。
main.c
- /*
- * This project is implemented for testing variable-argument
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include "log.h"
- FILE *fp_log = NULL;
- void main(char arg, char *argv[])
- {
- if ((fp_log = fopen("test.log", "w+")) == NULL)
- {
- printf("The file 'test.log' was not opened\n");
- }
- tc_log(fp_log, "%s", __FUNCTION__);
- tc_log(fp_log, "%s, %d", __FUNCTION__, 1);
- tc_log(fp_log, "%s, %d, %s, %d", __FUNCTION__, 2, __FUNCTION__, 2);
- if( fclose(fp_log))
- printf( "The file 'test.log' was not closed\n");
- }
- /*
- * File: log.h
- */
- #ifndef __LOG_H__
- #define __LOG_H__
- #include <stdarg.h>
- typedef char * va_list;
- extern FILE *fp_log;
- void tc_log(const FILE *fp_log, const char *fmt, ...);
- void tc_log_default(const FILE *fp_log, const char * fmt, va_list vl);
- #endif
- /*
- * File: log.c
- */
- #include "stdio.h"
- #include "log.h"
- void tc_log(const FILE *fp_log, const char *fmt, ...)
- {
- va_list vl;
- /* Macro to set 'vl' to beginning of list of optional arguments */
- va_start(vl, fmt);
-
- tc_log_default(fp_log, fmt, vl);
-
- /* Macro to reset arg_ptr */
- va_end(vl);
- return;
- }
- void tc_log_default(const FILE *fp_log, const char * fmt, va_list vl)
- {
- char line[1024];
- line[0] = 0;
- printf("strlen = %d, sizeof = %d\n", strlen(line), sizeof(line));
- vsnprintf(line + strlen(line), sizeof(line) - strlen(line), fmt, vl);
- fprintf(fp_log, "%s\n", line);
- return;
- }