문제
markdown
Assignment name : ft_printf
Expected files : ft_printf.c
Allowed functions: malloc, free, write, va_start, va_arg, va_copy, va_end
--------------------------------------------------------------------------------
Write a function named ft_printf that will mimic the real printf but
it will manage only the following conversions: s,d and x.
Your function must be declared as follows:
int ft_printf(const char *, ... );
Before you start we advise you to read the man 3 printf and the man va_arg.
To test your program compare your results with the true printf.
Exemples of the function output:
call: ft_printf("%s\n", "toto");
out: toto$
call: ft_printf("Magic %s is %d", "number", 42);
out: Magic number is 42%
call: ft_printf("Hexadecimal for %d is %x\n", 42, 42);
out: Hexadecimal for 42 is 2a$
Obs: Your function must not have memory leaks. Moulinette will test that.
ft_printf
c
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
void put_str(char *str, int *len)
{
if (!str)
{
(*len) += write(1, "(null)", 6);
return ;
}
while (*str)
(*len) += write(1, str++, 1);
}
void put_nbr(int n, int *len)
{
if (n == -2147483648)
{
(*len) += write(1, "-2147483648", 11);
return ;
}
if (n < 0)
{
(*len) += write(1, "-", 1);
n *= -1;
}
if (n >= 10)
put_nbr(n / 10, len);
(*len) += write(1, &"0123456789"[n % 10], 1);
}
void put_hex(unsigned int n, int *len)
{
if (n >= 16)
put_hex(n / 16, len);
(*len) += write(1, &"0123456789abcdef"[n % 16], 1);
}
int ft_printf(const char *str, ...)
{
int len = 0;
va_list ptr;
va_start(ptr, str);
while (*str)
{
if (*str == '%' && (*(str + 1) == 's' || *(str + 1) == 'd' || *(str + 1) == 'x'))
{
str++;
if (*str == 's')
put_str(va_arg(ptr, char *), &len);
else if (*str == 'd')
put_nbr(va_arg(ptr, int), &len);
else if (*str == 'x')
put_hex(va_arg(ptr, unsigned int), &len);
}
else
len += write(1, str, 1);
str++;
}
va_end(ptr);
return (len);
}