92 lines
2.3 KiB
C
92 lines
2.3 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_vsprintf.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2022/10/06 10:44:36 by cchauvet #+# #+# */
|
|
/* Updated: 2022/10/07 02:26:50 by cchauvet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "libftprintf.h"
|
|
|
|
static char *ft_argtoa(int c, va_list args)
|
|
{
|
|
if (c == 'c')
|
|
return (ft_ctoa(va_arg(args, int)));
|
|
if (c == 's')
|
|
return (ft_strdup(va_arg(args, char *)));
|
|
if (c == 'd' || c == 'i')
|
|
return (ft_itoa(va_arg(args, long int)));
|
|
if (c == 'p')
|
|
return (ft_ptoa(va_arg(args, void *)));
|
|
if (c == 'x')
|
|
return (ft_itoabase(va_arg(args, long int), "0123456789abcdef"));
|
|
if (c == 'X')
|
|
return (ft_itoabase(va_arg(args, long int), "0123456789ABCDEF"));
|
|
if (c == '%')
|
|
return (ft_ctoa('%'));
|
|
return (NULL);
|
|
}
|
|
|
|
static size_t ft_seglen(const char *str)
|
|
{
|
|
size_t i;
|
|
|
|
i = 0;
|
|
while (str[i] != 0 && str[i] != '%')
|
|
i++;
|
|
return (i);
|
|
}
|
|
|
|
static char *ft_strfjoin(char *s1, const char *s2)
|
|
{
|
|
size_t i;
|
|
size_t j;
|
|
char *out;
|
|
|
|
if (s1 == NULL || s2 == NULL)
|
|
return (NULL);
|
|
out = malloc((ft_seglen(s1) + ft_seglen(s2) + 1) * sizeof(char));
|
|
i = 0;
|
|
while (s1[i] != 0 && s2[i] != '%')
|
|
{
|
|
out[i] = s1[i];
|
|
i++;
|
|
}
|
|
free(s1);
|
|
j = 0;
|
|
while (s2[j] != 0 && s2[j] != '%')
|
|
{
|
|
out[i + j] = s2[j];
|
|
j++;
|
|
}
|
|
out[i + j] = 0;
|
|
return (out);
|
|
}
|
|
|
|
char *ft_vsprintf(char *str, const char *format, va_list va)
|
|
{
|
|
char *mid_out;
|
|
|
|
while (format != NULL)
|
|
{
|
|
str = ft_strfjoin(str, format);
|
|
format = ft_strchr(format, '%');
|
|
if (format == NULL)
|
|
break ;
|
|
else
|
|
format += 1;
|
|
mid_out = ft_argtoa(*format, va);
|
|
if (mid_out == NULL)
|
|
{
|
|
free(str);
|
|
return (0);
|
|
}
|
|
str = ft_strfjoin(str, mid_out);
|
|
}
|
|
return (str);
|
|
}
|