-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_printf.c
99 lines (90 loc) · 2.4 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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_printf.c :+: :+: */
/* +:+ */
/* By: jvan-hal <[email protected]> +#+ */
/* +#+ */
/* Created: 2022/10/20 13:25:50 by jvan-hal #+# #+# */
/* Updated: 2023/01/11 10:59:27 by jvan-hal ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
static int sectionlength(const char *s)
{
int count;
count = 0;
while (*s && *s != '%')
{
++count;
++s;
}
return (count);
}
static char *chartostr(int c)
{
char *str;
str = malloc(2);
if (!str)
return (NULL);
str[0] = (char)c;
str[1] = '\0';
return (str);
}
static int parser(const char **s, va_list args)
{
char *str;
char type;
t_padding padinfo;
s[0] += getformat(s[0], &padinfo);
type = *s[0];
if (type == 's')
str = va_arg(args, char *);
else if (type == 'p')
str = getstr_ptr(va_arg(args, uintptr_t), 'x', &padinfo);
else if (type == 'd' || type == 'i')
str = ft_itoa_format(va_arg(args, int), &padinfo);
else if (type == 'u')
str = ft_uitoa(va_arg(args, unsigned int), &padinfo);
else if (type == 'x' || type == 'X')
str = getstr_hex(va_arg(args, int), *s[0], &padinfo);
else if (type == 'c')
str = chartostr(va_arg(args, int));
else if (type == '%')
str = chartostr('%');
else
str = chartostr(type);
if (s[0])
++s[0];
return (ft_writestr(str, type, &padinfo));
}
int ft_printf(const char *s, ...)
{
int sectionlen;
int printlen;
va_list args;
printlen = 0;
va_start(args, s);
while (*s)
{
sectionlen = write(1, s, sectionlength(s));
if (sectionlen == -1)
return (-1);
s += sectionlen;
printlen += sectionlen;
if (*s)
{
if (!*(s + 1))
break ;
sectionlen = parser(&s, args);
if (sectionlen == -1)
return (-1);
printlen += sectionlen;
}
}
va_end(args);
return (printlen);
}