/ ft_printf / ft_printf / ft_printf.c
ft_printf.c
 1  /* ************************************************************************** */
 2  /*                                                                            */
 3  /*                                                        :::      ::::::::   */
 4  /*   ft_printf.c                                        :+:      :+:    :+:   */
 5  /*                                                    +:+ +:+         +:+     */
 6  /*   By: gychoi <gychoi@student.42seoul.kr>         +#+  +:+       +#+        */
 7  /*                                                +#+#+#+#+#+   +#+           */
 8  /*   Created: 2022/09/08 15:11:07 by gychoi            #+#    #+#             */
 9  /*   Updated: 2022/09/13 13:35:35 by gychoi           ###   ########.fr       */
10  /*                                                                            */
11  /* ************************************************************************** */
12  
13  #include "ft_printf.h"
14  
15  int	handle_specifier(va_list *ap, char spec)
16  {
17  	if (spec == 'c')
18  		return (print_char(va_arg(*ap, int)));
19  	else if (spec == 's')
20  		return (print_string(va_arg(*ap, char *)));
21  	else if (spec == 'p')
22  		return (print_address(va_arg(*ap, void *)));
23  	else if (spec == 'd' || spec == 'i')
24  		return (print_number(va_arg(*ap, int), "0123456789", 1));
25  	else if (spec == 'u')
26  		return (print_number(va_arg(*ap, unsigned int), "0123456789", 0));
27  	else if (spec == 'x')
28  		return (print_number(va_arg(*ap, unsigned int), "0123456789abcdef", 0));
29  	else if (spec == 'X')
30  		return (print_number(va_arg(*ap, unsigned int), "0123456789ABCDEF", 0));
31  	else if (spec == '%')
32  		return (print_char('%'));
33  	else
34  		return (-1);
35  }
36  
37  int	parsing_format(const char *format, va_list *ap)
38  {
39  	int	ret;
40  	int	printed;
41  
42  	printed = 0;
43  	while (*format)
44  	{
45  		if (*format == '%')
46  		{
47  			ret = handle_specifier(ap, *(++format));
48  			if (ret < 0)
49  				return (-1);
50  		}
51  		else
52  		{
53  			ret = (int)write(1, &(*format), 1);
54  			if (ret < 0)
55  				return (-1);
56  		}
57  		printed += ret;
58  		format++;
59  	}
60  	return (printed);
61  }
62  
63  int	ft_printf(const char *format, ...)
64  {
65  	va_list	ap;
66  	int		printed;
67  
68  	va_start(ap, format);
69  	printed = parsing_format(format, &ap);
70  	va_end(ap);
71  	if (printed < 0)
72  		return (-1);
73  	return (printed);
74  }