summaryrefslogtreecommitdiff
path: root/ft_printf.c
blob: 87655c57e65529c33aac3794508305acf2248dda (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
ft_printf
Copyright (C) 2026 yctct

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/


// 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);
}