-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_printf.c
More file actions
95 lines (90 loc) · 1.69 KB
/
Copy path_printf.c
File metadata and controls
95 lines (90 loc) · 1.69 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
90
91
92
93
94
95
#include <stdarg.h>
#include <stdlib.h>
#include "main.h"
/**
* print_args - prints the variadic function based on the specifier given
* @arr: array of spec_t containing specifiers and matched functions
* @spec: specifier char
* @args: va_list parameter
*
* Return: returns count of characters printed
*/
int print_args(spec_t *arr, char spec, va_list args)
{
int print_count = 0, index;
int (*func)(va_list) = NULL;
if (spec == '%')
{
_putchar('%');
print_count++;
return (print_count);
}
for (index = 0; arr[index].func != NULL; index++)
{
if (spec == arr[index].spec)
{
func = arr[index].func;
break;
}
}
if (func == NULL)
{
_putchar('%');
_putchar(spec);
print_count += 2;
return (print_count);
}
print_count = func(args);
return (print_count);
}
/**
* _printf - function similar to the printf();
* @format: format specifier string
*
* Return: count of characters printed to the stdout
*/
int _printf(const char *format, ...)
{
spec_t arr[] = {
{'c', print_char},
{'s', _puts},
{'d', print_number},
{'i', print_number},
{'u', print_unsigned_num},
{'b', print_binary},
{'o', print_octal},
{'x', printf_hex},
{'X', printf_HEX},
{'\0', NULL}
};
const char *fp = format;
int print_count = 0;
char spec;
va_list args;
if (format == NULL)
return (-1);
va_start(args, format);
while (fp && *fp)
{
if (*fp == '%')
{
fp++;/*move to next char after %*/
spec = *fp;
if (spec == '\0')
{
print_count += _putchar('%');
return (print_count);
}
print_count += print_args(arr, spec, args);
fp++;
}
else
{
_putchar(*fp);
print_count++;
fp++;
}
}
va_end(args); /* Added va_end */
return (print_count);
}