-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_printf.c
68 lines (61 loc) · 1.96 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rnishimo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/01 16:53:50 by rnishimo #+# #+# */
/* Updated: 2022/01/29 22:16:44 by rnishimo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static size_t _add_and_check_overflow(size_t print_size, size_t pre_size)
{
if (print_size > (size_t)SIZE_MAX - pre_size)
return ((size_t)SIZE_MAX);
return (print_size + pre_size);
}
void init_struct(t_str *st_str, t_flag *st_flag)
{
ft_memset(st_str, 0, sizeof(t_str));
ft_memset(st_flag, 0, sizeof(t_flag));
}
static int _vprintf(char *format, va_list ap)
{
size_t print_size;
size_t pre_size;
t_str st_str;
t_flag st_flag;
print_size = 0;
while (*format != '\0')
{
if (*format == '%')
{
init_struct(&st_str, &st_flag);
if (!parse(&format, ap, &st_str, &st_flag))
return (-1);
pre_size = print(&st_str, &st_flag);
print_size = _add_and_check_overflow(print_size, pre_size);
}
else
{
ft_putchar_fd(*(format++), STDOUT_FILENO);
print_size++;
}
if (print_size >= INT_MAX)
return (-1);
}
return ((int)print_size);
}
int ft_printf(const char *format, ...)
{
va_list ap;
int print_size;
if (format == NULL)
return (0);
va_start(ap, format);
print_size = _vprintf((char *)format, ap);
va_end(ap);
return (print_size);
}