-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_printf.c
78 lines (76 loc) · 1.43 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
#include <stdarg.h>
#include <unistd.h>
#include "main.h"
/**
* find_function - function that finds formats for _printf
* calls the corresponding function.
* @format: format (char, string, int, decimal)
* Return: NULL or function associated ;
*/
int (*find_function(const char *format))(va_list)
{
unsigned int i = 0;
code_f find_f[] = {
{"c", print_char},
{"s", print_string},
{"i", print_int},
{"d", print_dec},
{"b", print_bin},
{"o", print_octal},
{"x", print_x},
{"X", print_X},
{"r", print_rev},
{"u", print_unsig},
{"R", print_rot13},
{NULL, NULL}
};
while (find_f[i].sc)
{
if (find_f[i].sc[0] == (*format))
return (find_f[i].f);
i++;
}
return (NULL);
}
/**
* _printf - function that produces output according to a format.
* @format: format (char, string, int, decimal)
* Return: size the output text;
*/
int _printf(const char *format, ...)
{
va_list ap;
int (*f)(va_list);
unsigned int i = 0, cprint = 0;
if (format == NULL)
return (-1);
va_start(ap, format);
while (format[i])
{
while (format[i] != '%' && format[i])
{
_putchar(format[i]);
cprint++;
i++;
}
if (format[i] == '\0')
return (cprint);
f = find_function(&format[i + 1]);
if (f != NULL)
{
cprint += f(ap);
i += 2;
continue;
}
if (!format[i + 1])
return (-1);
_putchar(format[i]);
cprint++;
if (format[i + 1] == '%')
i += 2;
else
i++;
}
va_end(ap);
return (cprint);
}