-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path_dprintf.c
134 lines (126 loc) · 2.49 KB
/
_dprintf.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
130
131
132
133
134
#include "main.h"
/**
* _dprintf - prints only unsigned int and string datatype pass
* since that the most
* commonly use of this function on this shell
* project
* @fd: a file descriptor the user inputs
* @format: string pointer
* Return: len of the string
*/
int _dprintf(int fd, const char *format, ...)
{
va_list ap;
int index_arr_no, i = 0;
size_t count = 0;
specifiers_x formats[] = {
{'u', _ui_arg},
{'s', _string_arg},
{0, NULL}
};
if (!format)
return (-1);
va_start(ap, format);
while (format && format[i])
{
if (format[i] == '%')
{
i++;
index_arr_no = 0;
while (formats[index_arr_no].form_t)
{
if (format[i] == formats[index_arr_no].form_t)
{
count += formats[index_arr_no].call(&ap, fd);
break;
}
index_arr_no++;
}
if (formats[index_arr_no].form_t == 0)
count += write(fd, &format[i], 1);
}
else
count += write(fd, &format[i], 1);
i++;
}
va_end(ap);
return (count);
}
/**
* _string_arg - prints a string format type
* @ap: list of indefinite arguments number
* @fd: file descriptor to write to
* Return: 0 (success)
*/
int _string_arg(va_list *ap, int fd)
{
char *s;
s = va_arg(*ap, char *);
if (!s)
{
s = "(null)";
}
return ((unsigned int)(write(fd, s, _strlen(s))));
}
/**
* _ui_arg - returns an unsigned int value
*
* @ap: list of indefinite arguments
* @fd: file descriptor to write to
* Return: value to be printed
*/
int _ui_arg(va_list *ap, int fd)
{
int retrive = 0;
int mask = 0, mask_cpy = 0;
ui result = 0;
char *buf = NULL;
retrive = va_arg(*ap, int);
/* absolute functions */
mask = retrive >> (sizeof(int) * 8 - 1);
result = (retrive ^ mask) - mask;
buf = malloc(sizeof(char) * (digit_counter(result) + 1));
mask = 0;
while (result > 0)
{
buf[mask++] = (result % 10) + '0';
result /= 10;
}
mask_cpy = mask;
/* check me out here **^^ */
while (--mask_cpy >= 0)
{
write(fd, &buf[mask_cpy], 1);
}
free(buf);
return (mask);
}
/**
* digit_counter - counts the number of digits present
* @num: digits passed
* Return: number of digits present
*/
ui digit_counter(int num)
{
unsigned int temp = 0, count = 0;
temp = num;
count = (temp == 0) ? 1 : 0;
while (temp != 0)
{
temp /= 10;
count++;
}
return (count);
}
/**
* _char_arg - prints a char format type
* @ap: list of indefinite arguments number
* @fd: file descriptor to write to
* Return: 0 (success)
*/
int _char_arg(va_list *ap, int fd)
{
char x;
x = va_arg(*ap, int);
return ((unsigned int)(write(fd, &x, 1)));
}