-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_printf.c
146 lines (135 loc) · 2.35 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
int width, prc, count;
void ft_putchar(char c)
{
write(1, &c, 1);
count++;
}
char *ft_atoi(char *s, int *rtn)
{
while (*s >= '0' && *s <= '9')
{
*rtn = *rtn * 10 + (*s - '0');
s++;
}
return s;
}
char *get_type(char *s)
{
width = 0;
prc = -1;
if (*s)
s = ft_atoi(s, &width);
if (*s && *s == '.')
{
prc = 0;
s = ft_atoi(s + 1, &prc);
}
return s;
}
int length(unsigned int d, int base)
{
int len = 1;
while ((d /= base))
len++;
return len;
}
void ft_putnbr(unsigned int nbr, int base)
{
if (nbr < 10)
ft_putchar(nbr + '0');
else
{
if (nbr < 16 && base == 16)
ft_putchar(nbr + 'W');
else
{
ft_putnbr(nbr / base, base);
ft_putnbr(nbr % base, base);
}
}
}
void print_d(va_list pa)
{
int dd = va_arg(pa, int);
unsigned int d;
int max;
int len;
d = dd > 0 ? dd : -dd;
len = length(d, 10);
max = len > prc ? len : prc;
if (dd == 0 && prc == 0)
max = 0;
if (dd < 0)
max++;
int i = -1;
while (++i < width - max)
ft_putchar(' ');
if (dd < 0)
ft_putchar('-');
i = -1;
while (++i < prc - len)
ft_putchar('0');
if (dd != 0 || prc != 0)
ft_putnbr(d, 10);
}
void print_x(va_list pa)
{
unsigned int x = va_arg(pa, unsigned int);
int len = length(x, 16),
max = len > prc ? len : prc;
if (x == 0 && prc == 0)
max = 0;
int i = -1;
while (++i < width - max)
ft_putchar(' ');
i = -1;
while (++i < prc - len)
ft_putchar('0');
if (x != 0 || prc != 0)
ft_putnbr(x, 16);
}
void print_s(va_list pa)
{
char *s = va_arg(pa, char*);
if (s == NULL)
s = "(null)";
int len = -1, min;
while (s[++len]);
min = prc < 0 ? len : len < prc ? len : prc;
int i = -1;
while (++i < width - min)
ft_putchar(' ');
write(1, s, min);
count += min;
}
int ft_printf(const char *s, ...)
{
count = 0;
va_list pa;
va_start(pa, s);
int i = 0;
while (*s)
{
if (*s != '%')
ft_putchar(*s);
else
{
s = get_type((char*)s + 1);
if (*s == 'd')
print_d(pa);
if (*s == 'x')
print_x(pa);
if (*s == 's')
print_s(pa);
if (*s != 's' && *s != 'd' && *s != 'x')
s--;
}
s++;
}
va_end(pa);
return count;
}