-
Notifications
You must be signed in to change notification settings - Fork 0
/
_printf.c
executable file
·82 lines (78 loc) · 1.37 KB
/
_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
#include "main.h"
#include <stdlib.h>
/**
* check_for_specifiers - checks if there is a valid format specifier
* @format: possible format specifier
*
* Return: pointer to valid function or NULL
*/
static int (*check_for_specifiers(const char *format))(va_list)
{
unsigned int i;
print_t p[] = {
{"c", print_c},
{"s", print_s},
{"i", print_i},
{"d", print_d},
{"u", print_u},
{"b", print_b},
{"o", print_o},
{"x", print_x},
{"X", print_X},
{"p", print_p},
{"S", print_S},
{"r", print_r},
{"R", print_R},
{NULL, NULL}
};
for (i = 0; p[i].t != NULL; i++)
{
if (*(p[i].t) == *format)
{
break;
}
}
return (p[i].f);
}
/**
* _printf - prints anything
* @format: list of argument types passed to the function
*
* Return: number of characters printed
*/
int _printf(const char *format, ...)
{
unsigned int i = 0, count = 0;
va_list valist;
int (*f)(va_list);
if (format == NULL)
return (-1);
va_start(valist, format);
while (format[i])
{
for (; format[i] != '%' && format[i]; i++)
{
_putchar(format[i]);
count++;
}
if (!format[i])
return (count);
f = check_for_specifiers(&format[i + 1]);
if (f != NULL)
{
count += f(valist);
i += 2;
continue;
}
if (!format[i + 1])
return (-1);
_putchar(format[i]);
count++;
if (format[i + 1] == '%')
i += 2;
else
i++;
}
va_end(valist);
return (count);
}