-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprintf.c
More file actions
89 lines (77 loc) · 1.56 KB
/
printf.c
File metadata and controls
89 lines (77 loc) · 1.56 KB
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
#include "holberton.h"
#include <stdarg.h>
#include <stdlib.h>
/**
* interpolate - Assist printf with data interpolation in @string
*
* @format: The main string passed in to be printed
* @i: Index in @format when interpolation is triggered
* @ap: Variadic list containing arguments to be processed
* @length: Total length of @format up to current processing
*
* Return: (i) to printf so it may continue to process @format
*/
int interpolate(const char *format, int i, va_list ap, int length)
{
int escape = 0, j = 0;
print fmt[] = {
{"c", print_char}, {"s", print_string},
{"i", print_int}, {"d", print_int},
{"b", print_bin}, {NULL, NULL}
};
while (fmt[j].form != NULL)
{
if (*(fmt[j].form) == format[i + 1])
{
length += fmt[j].f(ap);
i++;
escape = 1;
}
j++;
}
if (escape == 0)
{
_putchar('%');
length++;
if (format[i + 1] != '%')
{
_putchar(format[i + 1]);
length++;
}
i++;
}
return (length);
}
/**
* _printf - Print @format and interpolate data as needed
*
* @format: The main string passed in to be printed
*
* Return: (0) Success
*/
int _printf(const char *format, ...)
{
va_list ap;
int i = 0, length = 0;
if (format == NULL)
return (-1);
va_start(ap, format);
while (format[i] != '\0')
{
if (format[i] == '%')
{
if (format[i + 1] == '\0')
return (-1);
length = interpolate(format, i, ap, length);
i++;
}
else
{
_putchar(format[i]);
length++;
}
i++;
}
va_end(ap);
return (length);
}