-
Notifications
You must be signed in to change notification settings - Fork 2
/
ft_printf.c
83 lines (77 loc) · 2.16 KB
/
ft_printf.c
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mcil <mcil@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/20 11:04:10 by mcil #+# #+# */
/* Updated: 2022/02/26 16:52:26 by mcil ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_scan(char c, va_list macro)
{
if (c == 'c')
return (ft_putchar(va_arg(macro, int)));
else if (c == 's')
return (ft_putstr(va_arg(macro, char *)));
else if (c == 'p')
{
ft_putstr("0x");
return (ft_putpointer(va_arg(macro, void *)) + 2);
}
else if (c == 'd' || c == 'i')
return (ft_putnbr(va_arg(macro, int)));
else if (c == 'u')
return (ft_putstr(
ft_convert(va_arg(macro, unsigned int), "0123456789")));
else if (c == '%')
return (ft_putchar('%'));
else if (c == 'x')
return (ft_putstr(
ft_convert(va_arg(macro, unsigned int), "0123456789abcdef")));
else if (c == 'X')
return (ft_putstr(
ft_convert(va_arg(macro, unsigned int), "0123456789ABCDEF")));
return (0);
}
char *ft_convert(unsigned int num, char *set)
{
static char buffer[50];
char *ptr;
int base;
base = ft_strlen(set);
ptr = &buffer[49];
*ptr = '\0';
*--ptr = set[num % base];
num /= base;
while (num != 0)
{
*--ptr = set[num % base];
num /= base;
}
return (ptr);
}
int ft_printf(const char *sign, ...)
{
va_list macro;
int i;
int len;
va_start(macro, sign);
i = 0;
len = 0;
while (sign[i])
{
if (sign[i] == '%')
{
len += ft_scan(sign[i + 1], macro);
i++;
}
else
len += write(1, &sign[i], 1);
i++;
}
va_end(macro);
return (len);
}