I am trying to not only return the output to the stdout
but also trying to return the size of each data type that would be tested. I am using the write()
syscall to write the simple output to the stdout
(and yes I am sticking to write()
since it is more efficient space + time complexity wise) on my else
statement but I'm not sure about the logic of each of the case
clauses for each variable conversion. Also any feedback on my code organization would also be greatly appreciated as well as any feedback at all whatsoever.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdint.h>
char *convert(unsigned int, int);
int my_printf(char *format, ...)
{
va_list args;
va_start(args, format);
unsigned int i;
char *input;
char *s;
void *p;
for (input = format; *input != '\0'; input++)
{
if (*input == '%') {
input++;
//FETCH & EXECUTE VARIABLE CONVERSION
switch (*input)
{
case '%': write(1, "%", 1);
break;
case 'd': i = va_arg(args, int);
if (i <= 0)
{
i = -i;
write(1, "-", 1);
}
write(1, convert(i, 10), strlen(convert(i, 10)));
break;
case 'o': i = va_arg(args, unsigned int);
write(1, convert(i, 8), strlen(convert(i, 8)));
break;
case 'u': i = va_arg(args, unsigned int);
write(1, convert(i, 10), strlen(convert(i, 10)));
break;
case 'x': i = va_arg(args, unsigned int);
write(1, convert(i, 16), strlen(convert(i, 16)));
break;
case 'c': i = va_arg(args, int);
write(1, &i, 1);
break;
case 's': s = va_arg(args, char *);
write(1, s, strlen(s));
break;
case 'p': p = va_arg(args, void*);
intptr_t ptr_val = (intptr_t)p;
write(1, convert(ptr_val, 16), strlen(convert(ptr_val, 16)));
break;
default: write(1, input - 1, 2);
break;
}
}
else
{
write(1, input, 1);
}
}
va_end(args);
return 0;
}
char *convert(unsigned int n, int base)
{
static char Rep[] = "0123456789ABCDEF";
static char buffer[50];
char *ptr;
ptr = &buffer[49];
*ptr = '\0';
do
{
*--ptr = Rep[n % base];
n /= base;
}
while (n != 0);
return (ptr);
}
I tried using strlen()
inside of write()
for each case but I am not getting back a data byte size value, which I thought could work with strlen()
. I also tried size_t
and sizeof
in place of strlen()
which did not work.