曲径通幽论坛

标题: vsprintf(), vsnprintf() | 打印输出 [打印本页]

作者: beyes    时间: 2009-10-14 22:52
标题: vsprintf(), vsnprintf() | 打印输出
函数原型
#include <stdarg.h>
int vsprintf(char *str, const char *format, va_list ap);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);

说明
vsprintf() 和 vsnprintf() 基本一样,但后者比前者多了一个字节数的限定。

vsprintf() 参数说明
str  : 一般是个字符缓冲区的首地址;
format : 是带有格式说明的字符串,如同 printf() 中第一个参数;
ap : va_list 类型,关于 va_list 类型说明见:http://www.groad.net/bbs/read.php?tid-947.html

应用举例
#include <stdio.h>
#include <stdarg.h>

void log_msg (const char *text, ...)
{
         char buf [256];

         va_list args;

         va_start (args, text);

         vsprintf (buf , text, args);

         printf ("%s", buf);

         va_end (args);
}


int main()
{
         int year = 2008;
         char *ptr = "china";

         log_msg ("hello %d Beijing and welcome to %s\n", year, ptr);

         return (0);
}
      

运行与输出
[beyes@localhost vsprintf]$ ./vsprintf.exe
hello 2008 Beijing and welcome to china

从输出可见,在 log_msg() 函数中,输入到 buf 数组里的内容,是经过格式转换后的内容,不是把 %d , %s 这样的格式原本不动的照搬到 buf 数组中。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2