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

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

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

使用va_list编写可变参数的函数使用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/
原文链接: https://www.cnblogs.com/stuarts/archive/2010/08/03/1791598.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/13362

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午12:44
下一篇 2023年2月7日 下午12:44

相关推荐