使用va_list编写可变参数的函数

在c和c++中,可变参数使用的最多函数有:scanf,printf,以及fprintf,fscanf,sprintf等,MFC也提供CString::Format实现可变参数。

本文提供用va_list实现自己的可变参数函数,应用场合包括:程序的写日志功能。示例代码如下:

代码
1 #include <stdio.h>
2 #include <stdarg.h>
3
4  void WriteLog(char * format, ...)
5 {
6 char buffer[256];
7 va_list args;
8 va_start (args, format);
9 vsprintf (buffer,format, args);
10
11 FILE* pFile = fopen("log.txt","a+");
12 fprintf(pFile,buffer);
13 fclose(pFile);
14
15 va_end (args);
16 }
17
18 int main ()
19 {
20 WriteLog("%s %d %d","222",1,3);
21 int i;
22 scanf("%d",&i);
23 return 0;
24 }
25

 

参考文献:

http://www.cplusplus.com/reference/clibrary/cstdio/vsprintf/

posted @ 2010-08-03 22:41  stuarts  Views(724)  Comments(0Edit  收藏  举报