1.myprintf.c
#include "inc/myprintf.h"
#include <stdarg.h>
#include <stdio.h>
#include "inc/main.h"
#define putc MyPutChar
/*
* Conver int to string based on radix (usually 2, 8, 10, and 16)
*/
char *itoa(int num, char *str, int radix)
{
char string[] = "0123456789abcdefghijklmnopqrstuvwxyz";
char* ptr = str;
int i;
int j;
while (num)
{
*ptr++ = string[num % radix];
num /= radix;
if (num < radix)
{
*ptr++ = string[num];
*ptr = '\0';
break;
}
}
j = ptr - str - 1;
for (i = 0; i < (ptr - str) / 2; i++)
{
int temp = str;
str = str[j];
str[j--] = temp;
}
return str;
}
/*
* A simple printf function. Only support the following format:
* Code Format
* %c character
* %d signed integers
* %i signed integers
* %s a string of characters
* %o octal
* %x unsigned hexadecimal
*/
int my_printf( const char* format, ...)
{
va_list arg;
int done = 0;
va_start (arg, format);
//done = vfprintf (stdout, format, arg);
while( *format != '\0')
{
if( *format == '%')
{
if( *(format+1) == 'c' )
{
char c = (char)va_arg(arg, int);
// putc(c, stdout);
putc(c);
} else if( *(format+1) == 'd' || *(format+1) == 'i')
{
char store[20];
int i = va_arg(arg, int);
char* str = store;
itoa(i, store, 10);
while( *str != '\0')
// putc(*str++, stdout);
putc(*str++);
} else if( *(format+1) == 'o')
{
char store[20];
int i = va_arg(arg, int);
char* str = store;
itoa(i, store, 8);
while( *str != '\0')
// putc(*str++, stdout);
putc(*str++);
} else if( *(format+1) == 'x')
{
char store[20];
int i = va_arg(arg, int);
char* str = store;
itoa(i, store, 16);
while( *str != '\0')
// putc(*str++, stdout);
putc(*str++);
} else if( *(format+1) == 's' )
{
char* str = va_arg(arg, char*);
while( *str != '\0')
// putc(*str++, stdout);
putc(*str++);
}
// Skip this two characters.
format += 2;
} else {
// putc(*format++, stdout);
putc(*format++);
}
}
va_end (arg);
return done;
} |