summaryrefslogtreecommitdiff
path: root/ft_printf.c
blob: 1058f5b7bff6657201b0d563d4aced00c8c2431f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

// for specifier 'c', we use int because char will be promoted to
// int anyway
//
// we store address of pointer in variable cause variadic
//
// ap: argument pointer
// ap gets incremented on each call
//
// a pointer pointing to the first flag/argument
// format states how many arguments are there
//
// va_start initialise the vector argument
//
// *format is the whole string printed by printf
//
// the last condition of ft_whichspecifier is to deal with 
// specifier followed by a non-conversion specifier

#include "ft_printf.h"

int	ft_whichspecifier(va_list ap, const char *format)
{
	int	counter;

	counter = 0;
	if (*format == 'c')
		counter += ft_putchar((char)(va_arg(ap, int)));
	else if (*format == 's')
		counter += ft_putstr((va_arg(ap, char *)));
	else if (*format == 'i' || *format == 'd')
		counter += ft_putnbr((va_arg(ap, int)));
	else if (*format == 'u')
		counter += ft_putunsigned((va_arg(ap, unsigned int)));
	else if (*format == 'x')
		counter += ft_puthexlower((va_arg(ap, unsigned int)));
	else if (*format == 'X')
		counter += ft_puthexupper((va_arg(ap, unsigned int)));
	else if (*format == 'p')
		counter += ft_checkpadd(ap);
	else if (*format == '%')
		counter += write(1, "%", 1);
	else 
	{
		counter += write(1, "%", 1);
		//counter += ft_putchar(*format);
		counter += write(1, &(*format), 1);
	}
	return (counter);
}

int	ft_printf(const char *format, ...)
{
	int		counter;
	va_list	ap;

	va_start(ap, format);
	counter = 0;
	if (!format)
		return (-1);
	while (*format)
	{
		if (*format == '%')
		{
			format++;
			counter += ft_whichspecifier(ap, format);
		}
		else
			counter += ft_putchar(*format);
		format++;
	}
	return (counter);
}