-
Notifications
You must be signed in to change notification settings - Fork 0
/
_printf.c
80 lines (78 loc) · 1.54 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
#include "main.h"
/**
*_printf - prints formatted arguments to stdout
*@format: Format specifier
*@...: optional arguments
*
*Return: int. Returns size of output buffer
*/
int _printf(const char *format, ...)
{
char *buffer, *alias, *stringize;
int length = bufLen(format);
int size = 0, i = 0;
char specifier;
char *token = malloc(2);
va_list nxt_param;
buffer = NULL, stringize = NULL;
va_start(nxt_param, format);
while (i < length)
{
if (format[i] != '%')
{
alias = buffer;
token[0] = format[i];
token[1] = '\0';
buffer = _concat(buffer, token);
if (alias != NULL)
{
free(alias);
}
i++;
}
else
{
alias = buffer;
specifier = format[i + 1];
switch (specifier)
{
case 'c':
token[0] = va_arg(nxt_param, int);
token[1] = '\0';
buffer = _concat(buffer, token);
break;
case '%':
token[0] = specifier;
token[1] = '\0';
buffer = _concat(buffer, token);
break;
case 's':
stringize = va_arg(nxt_param, char*);
buffer = _concat(buffer, stringize);
break;
case 'd':
stringize = to_string(va_arg(nxt_param, int));
buffer = _concat(buffer, stringize);
break;
case 'i':
stringize = to_string(va_arg(nxt_param, int));
buffer = _concat(buffer, stringize);
break;
default:
buffer = "Error: expected specifier-list";
break;
}
if (alias != NULL)
{
free(alias);
}
i = i + 2;
}
}
va_end(nxt_param);
size = bufLen(buffer);
write(1, buffer, size);
free(buffer);
free(token);
return (size);
}