#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int my_printf(const char *format, ...) {
va_list ap;
#define BUF_SIZE (1024)
#define STR_SIZE (64)
char buf[BUF_SIZE] = {0};
char c;
char *pos = buf;
va_start(ap, format);
while((c = *format)) {
if (c == '%') {
format++;
c = *format;
switch(c) {
case 'd':
{
int value = va_arg(ap, int);
char str[STR_SIZE] = {0};
sprintf(str, "%d", value);
memcpy(pos, str, strlen(str));
pos += strlen(str);
break;
}
case 'u':
{
unsigned int value = va_arg(ap, unsigned int); char str[STR_SIZE] = {0}; sprintf(str, "%u", value); memcpy(pos, str, strlen(str));
pos += strlen(str);
break;
}
case 'o':
{
unsigned int value = va_arg(ap, unsigned int); char str[STR_SIZE] = {0}; sprintf(str, "%o", value); memcpy(pos, str, strlen(str));
pos += strlen(str);
break;
}
case 'x':
{
unsigned int value = va_arg(ap, unsigned int); char str[STR_SIZE] = {0}; sprintf(str, "%x", value); memcpy(pos, str, strlen(str));
pos += strlen(str);
break;
}
case 'c':
{
char value = va_arg(ap, int);
memcpy(pos, &value, 1);
pos++;
break;
}
break;
case 's':
{
char *value = va_arg(ap, char *);
memcpy(pos, value, strlen(value));
pos += strlen(value);
break;
}
case 'p':
{
long long *value = va_arg(ap, long long *); char str[STR_SIZE] = {0}; sprintf(str, "%p", value); memcpy(pos, str, strlen(str));
pos += strlen(str);
break;
}
case '%':
{
memcpy(pos, &c, 1);
pos++;
break;
}
default:
{
printf("format error");
return -1;
}
}
} else {
memcpy(pos, &c, 1);
pos++;
}
format++;
}
write(2, buf, strlen(buf));
return 0;
}
int main(int argc, char *argv[]) {
int num = 0;
my_printf("%d,%u,%o,%x,%c,%s,%p,%%\n", 1234, 1234, 1234, 1234, 'a', "myprintf", &num);
return 0;
}