42_ft_printf/ft_vsprintf.c
Camille Chauvet af946dbf97 v1
2022-10-10 19:33:47 +02:00

106 lines
2.7 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_vsprintf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/06 10:44:36 by cchauvet #+# #+# */
/* Updated: 2022/10/10 19:32:04 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "printf.h"
static size_t ft_seglen(const char *str)
{
size_t i;
i = 0;
while ((str[i] != 0 && str[i] != '%') || (str[i] == '%' && i == 0))
i++;
return (i);
}
static char *ft_strfjoin(char *s1, char *s2)
{
size_t i;
size_t j;
char *out;
out = malloc((ft_strlen(s1) + ft_seglen(s2) + 1) * sizeof(char));
if (out == NULL)
return (NULL);
i = 0;
while (s1[i] != 0)
{
out[i] = s1[i];
i++;
}
free(s1);
j = 0;
while ((s2[j] != 0 && s2[j] != '%') || (s2[j] == '%' && j == 0))
{
out[i + j] = s2[j];
j++;
}
free(s2);
out[i + j] = 0;
return (out);
}
static char *ft_argtoa(int c, va_list args)
{
char *out;
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_ltoabase(va_arg(args, long int), "0123456789abcdef"));
if (c == 'X')
return (ft_ltoabase(va_arg(args, long int), "0123456789ABCDEF"));
if (c == 'u')
return (ft_ultoabase(va_arg(args, unsigned long int), "0123456789"));
if (c == '%')
return (ft_strdup("%"));
out = ft_strdup("% ");
if (out == NULL)
return (NULL);
out[1] = c;
return (out);
}
char *ft_vsprintf(char *str, const char *format, va_list va)
{
char *cformat;
char *ccformat;
char *mid;
cformat = ft_strdup(format);
ccformat = cformat;
if (str == NULL || cformat == NULL)
return (0);
while (cformat != NULL)
{
if (cformat[0] != '%')
str = ft_strfjoin(str, ft_strdup(cformat));
cformat = ft_strchr(cformat, '%');
if (cformat == NULL)
break ;
cformat += 1;
mid = ft_argtoa(cformat[0], va);
while (mid == NULL)
mid = ft_strdup("(null)");
str = ft_strfjoin(str, mid);
cformat += 1;
}
free(ccformat);
return (str);
}