- 论坛徽章:
- 0
|
printf 函数实现,代码仅供参考
#include <stdarg.h>
/***
void va_start(va_list ap, last);
type va_arg(va_list ap, type);
void va_end(va_list ap);
void va_copy(va_list dest, va_list src);
***/
void xPrintf(int LEVEL, const char* format, ...);
void xPrintf(int LEVEL, const char* format, ...)
{
va_list ap;
va_start(ap, format);
char buf[4096];
char *p = buf;
const char *f = format;
while (*f != '\0')
{
if (*f != '%')
{
*p++ = *f++;
continue;
}
++f;
int value;
char *pl;
char *pr;
char *tmp;
switch(*f++) {
case 'd':
value = va_arg(ap, int);
if (value < 0)
{
*p++ = '-';
value = ~value;
}
pl = p;
do {
*p++ = value%10+'0';
} while ((value /=10) > 0);
pr = p-1;
// swap
while(pr-pl > 0)
{
char t = *pl;
*pl = *pr;
*pr = t;
pl++; pr--;
}
break;
case 's':
tmp = va_arg(ap, char*);
while(*tmp != '\0')
{
*p++ = *tmp++;
}
break;
}
}
va_end(ap);
*p = '\0';
printf("%s\r\n", buf);
} |
|