-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_sprint.c
129 lines (121 loc) · 2.3 KB
/
my_sprint.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "main.h"
/**
* handle_character - handle character
* @outbuf: output buffer
* @written: number of characters written
* @fmt: format string
*
* Return: number of characters write
*
* Description: handle character
*
* 1. write character to outbuf
* 2. increment written
* 3. increment fmt
* 4. return
*
*/
void handle_character(char *outbuf, int *written, const char **fmt)
{
outbuf[(*written)++] = *(*fmt)++;
}
/**
* handle_integer - handle integer
* @outbuf: output buffer
* @written: number of characters written
* @args: variable arguments
* @fmt: format string
*
* Return: number of characters write
*
*/
void handle_integer(char *outbuf, int *written,
va_list *args, const char **fmt)
{
int i = 0, num = va_arg(*args, int);
char numStr[12];
custom_snpt(numStr, sizeof(numStr), "%d", num);
while (numStr[i])
{
outbuf[(*written)++] = numStr[i++];
}
(*fmt)++;
}
/**
* handle_string - handle string
* @outbuf: output buffer
* @written: number of characters written
* @args: variable arguments
* @fmt: format string
*
* Return: number of characters write
*
* Description: handle string
*
* 1. get string from args
* 2. if string is not null
* 3. while string is not null
* 4. write character to outbuf
* 5. increment written
* 6. increment string
* 7. increment fmt
* 8. return
*
*/
void handle_string(char *outbuf, int *written, va_list *args, const char **fmt)
{
char *str = va_arg(*args, char *);
if (str != NULL)
{
while (*str)
{
outbuf[(*written)++] = *str++;
}
}
(*fmt)++;
}
/**
* my_sprintf - custom sprintf
* @outbuf: output buffer
* @fmt: format string
* @...: variable arguments
*
* Return: number of characters written
*
*/
int my_sprintf(char *outbuf, const char *fmt, ...)
{
va_list args;
int written = 0;
va_start(args, fmt);
while (*fmt)
{
if (*fmt != '%')
{
handle_character(outbuf, &written, &fmt);
continue;
}
fmt++;
switch (*fmt)
{
case 'c':
outbuf[written++] = (char)va_arg(args, int);
fmt++;
break;
case 'd':
case 'i':
handle_integer(outbuf, &written, &args, &fmt);
break;
case 's':
handle_string(outbuf, &written, &args, &fmt);
break;
default:
outbuf[written++] = '%';
outbuf[written++] = *fmt++;
break;
}
}
va_end(args);
outbuf[written] = '\0';
return (written);
}