/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gvoelkne +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2026/04/29 09:00:02 by gvoelkne #+# #+# */ /* Updated: 2026/05/06 16:46:07 by gvoelkne ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static int ft_putstr(char *s) { ssize_t write_count; if (!s) return (ft_putstr("(null)")); write_count = write(1, s, ft_strlen(s)); if (write_count < 0) return (0); return (write_count); } static int ft_putchar(int c) { ssize_t write_count; write_count = write(1, &c, 1); if (write_count < 0) return (0); return (1); } static int format_alloc(char format, va_list args) { char *str; int result; if (format == 'd' || format == 'i') str = ft_ntoa(va_arg(args, int), 10); if (format == 'u') str = ft_untoa((unsigned int)va_arg(args, int), 10); if (format == 'X') str = ft_untoa(va_arg(args, unsigned int), 16); if (format == 'x') { str = ft_untoa(va_arg(args, unsigned int), 16); if (str) str = ft_strlower(str); } if (!str) return (0); result = ft_putstr(str); free(str); return (result); } static int format(char format, va_list args) { if (format == 'c') return (ft_putchar(va_arg(args, int))); if (format == 's') return (ft_putstr(va_arg(args, char *))); if (format == 'p') return (ft_putptr(va_arg(args, void *))); if (format == '%') return (ft_putchar('%')); return (format_alloc(format, args)); } int ft_printf(const char *s, ...) { int idx; int total; va_list args; idx = 0; total = 0; va_start(args, s); if (!s) return (-1); while (s[idx]) { if (s[idx] == '%' && s[idx + 1]) { idx += 1; if (!ft_strcontains("csp%diuXx", s[idx])) return (va_end(args), -1); total += format(s[idx], args); } else (write(1, &s[idx], 1), total += 1); idx += 1; } va_end(args); return (total); }