-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_printf.c
102 lines (95 loc) · 2.76 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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_printf.c :+: :+: */
/* +:+ */
/* By: cherrewi <[email protected]> +#+ */
/* +#+ */
/* Created: 2022/10/23 20:30:20 by cherrewi #+# #+# */
/* Updated: 2023/02/08 16:05:16 by cherrewi ######## odam.nl */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
/*
validates the format
returns the number of formats, or -1 in case the format string is invalid
a '%' sign should be followed by a format char
2 consequtive '%%' chars in the format string are printed '%'
*/
static int format_valid(const char *format_str, char *format_chars)
{
int format_count;
int i;
if (!format_str || !format_chars)
return (-1);
i = 0;
format_count = 0;
while (format_str[i])
{
if (format_str[i] == '%')
{
if (format_str[i + 1] && ft_strchr(format_chars, format_str[i + 1]))
{
i++;
format_count++;
}
else if (format_str[i + 1] == '%')
i++;
else
return (-1);
}
i++;
}
return (format_count);
}
static void print_va_arg(const char format_char, int *print_len, va_list ap)
{
char c;
if (format_char == 'c')
{
c = va_arg(ap, int);
*print_len += write(1, &c, 1);
}
if (format_char == 's')
printf_putstr(va_arg(ap, char *), print_len);
if (format_char == 'p')
{
*print_len += write(1, "0x", 2);
printf_putunsignedhex(va_arg(ap, unsigned long long int),
print_len, 'l');
}
if (format_char == 'd' || format_char == 'i')
printf_putnbr(va_arg(ap, int), print_len);
if (format_char == 'u')
printf_putunsnbr(va_arg(ap, unsigned int), print_len);
if (format_char == 'x')
printf_putunsignedhex(va_arg(ap, unsigned int), print_len, 'l');
if (format_char == 'X')
printf_putunsignedhex(va_arg(ap, unsigned int), print_len, 'u');
if (format_char == '%')
*print_len += write(1, "%", 1);
}
int ft_printf(const char *format, ...)
{
va_list ap;
char *format_chars;
int print_len;
va_start(ap, format);
format_chars = "cspdiuxX";
print_len = 0;
if (format_valid(format, format_chars) < 0)
return (-1);
while (*format)
{
if (*format == '%')
{
format++;
print_va_arg(*format, &print_len, ap);
}
else
print_len += write(1, format, 1);
format++;
}
va_end(ap);
return (print_len);
}