-
Notifications
You must be signed in to change notification settings - Fork 7
/
print_format.c
124 lines (107 loc) · 2.09 KB
/
print_format.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
#include "holberton.h"
#include <stdlib.h>
/**
* _print_format - Prints a format
* @format: The format to prints
* @args: A list of variadic arguments
*
* Return: The length of the format
*/
int _print_format(const char *format, va_list args)
{
int count = 0;
int i = 0;
while (format && format[i])
{
if (format[i] == '%')
{
if (format[i + 1] == '\0')
return (-1);
i++;
while (format[i] == ' ')
i++;
if (format[i] == '%')
count += _write(format[i]);
if (_validate_char(format[i]) == 0)
{
count = _print_invalid_spec(format[i - 1], format[i], count);
}
else
{
count += _print_spec(format[i], args);
}
}
else
{
count += _write(format[i]);
}
i++;
}
return (count);
}
/**
* _print_spec - Prints a valid specifier
* @format: The specifier to prints
* @args: A list of variadic arguments
*
* Return: The length of the specifier
*/
int _print_spec(char format, va_list args)
{
int i = 0, length = 0;
spc_dt _types[] = {
{"c", _print_a_char},
{"s", _print_a_string},
{"d", _print_a_integer},
{"i", _print_a_integer},
{"b", _print_int_binary},
{NULL, NULL}
};
while (_types[i].specifier)
{
if (*_types[i].specifier == format)
length = _types[i].f(args);
i++;
}
return (length);
}
/**
* _print_invalid_spec - Prints a invalid specifier
* @prev_format: The previous specifier of actual specifier
* @format: The specifier to prints
* @count: The current count before prints invalid specifiers
*
* Return: The current count after prints invalid specifiers
*/
int _print_invalid_spec(char prev_format, char format, int count)
{
count += _write('%');
if (prev_format == ' ')
{
count += _write(' ');
count += _write(format);
}
else
{
count += _write(format);
}
return (count);
}
/**
* _validate_char - validate the type
* @_type: character to be comparate
*
* Return: 1 if char is equal to a type
*/
int _validate_char(char _type)
{
char _types[] = {'c', 's', 'd', 'i', 'b', '%'};
int i = 0;
while (_types[i])
{
if (_types[i] == _type)
return (1);
i++;
}
return (0);
}