VC++6.0上写了个printf类似的程序,欢迎提出改进方法.
#include <stdio.h>#include <stdarg.h>
#include <string.h>
#ifndef NULL
#define NULL (void *)0 /* NULL : Null pointer */
#endif
#define putc_to_file(_c,_stream) (--(_stream)->_cnt >= 0 ?\
0xff & (*(_stream)->_ptr++ = (char)(_c)) : _flsbuf((_c),(_stream)))
void outputch(char ch)
{
putc_to_file(ch, stdout);
#if 0
(*(volatile unsigned short *)(0x80130000)) = (unsigned short)ch;
#endif
}
void outputstr(char *str)
{
puts(str);
}
void print_x(long l)
{
unsigned long t;
signed long i, k ;
signed char buf[8];
if (l == 0)
{
outputch('0');
return;
}
memset(buf,'0',8);
t = l;
k = 7;
for(;;)
{
if (t > 15)
{
i = t % 16;
}else
i = t;
if (i < 10){
buf[k--] = i + '0';
}
else
if(i < 16)
{
buf[k--] = i -10 +'a';
}
if (t < 15)
break;
t >>= 4;
}
for(i =0 ;i < 8 ; i ++)
outputch(buf[i]);
}
void print_0nx(char ch2, long l)
{
unsigned char ch;
int i;
ch2 = ch2 - '0';
for (i = ch2 - 1; i >= 0; i--) {
ch = (l >> (i * 4)) & 0x0f;
if (ch < 10)
outputch((char)(ch + '0'));
else
outputch((char)(ch - 10 + 'a'));
}
}
void print_d(long l)
{
unsigned long t;
int i, j, k ;
char buf[8];
if (l == 0)
{
outputch('0');
return;
}
memset(buf,'0',8);
t = l;
k = 7;
for(;;)
{
if (t > 9)
{
i = t % 10;
}else
i = t;
if (i < 10){
buf[k--] = i + '0';
}
if (t < 9)
break;
t /= 10;
}
j = 0;
for(i =0 ;i < 8 ; i ++)
{
if(buf[i] != '0')
j = 1;
if (j)
outputch(buf[i]);
}
}
int print_u(char *s, ...)
{
va_list ap;
unsigned long arg;
char *str;
char ch1, ch2, ch3;
va_start(ap, s);
while (*s != 0) {
if (*s == '%') {
s++;
ch1 = *s++;
if (ch1 == 's') {
str = va_arg(ap, char *);
outputstr(str);
}else if (ch1 == 'd') {
arg = va_arg(ap, long);
print_d(arg);
}
else if (ch1 == 'x') {
arg = va_arg(ap, long);
print_x(arg);
}else {
ch2 = *s++;
ch3 = *s++;
arg = va_arg(ap, long);
print_0nx(ch2, arg);
}
} else
outputch(*s++);
}
va_end(ap);
return 0;
}
int debug_printf(char *s, ...)
{
va_list ap;
unsigned long arg;
char *str;
char ch1, ch2, ch3;
va_start(ap, s);
while (*s != 0) {
if (*s == '%') {
s++;
ch1 = *s++;
if (ch1 == 's') {
str = va_arg(ap, char *);
print_u(str);
}else if (ch1 == 'd') {
arg = va_arg(ap, long);
print_d(arg);
}
else if (ch1 == 'x') {
arg = va_arg(ap, long);
print_x(arg);
}else {
ch2 = *s++;
ch3 = *s++;
arg = va_arg(ap, long);
print_0nx(ch2, arg);
}
} else
outputch(*s++);
}
va_end(ap);
return 0;
}
void main(void)
{
debug_printf("This is a printf test func, %s, %d \n", __FILE__, __LINE__);
debug_printf("*************AUTHOR :Young ************\n");
}