-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_printf.c
More file actions
131 lines (123 loc) · 2.24 KB
/
_printf.c
File metadata and controls
131 lines (123 loc) · 2.24 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
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
#include <unistd.h>
#include <stdarg.h>
#include "main.h"
/**
* print_number - Helper function to print an integer
* @n: The integer to print
*/
void print_number(int n)
{
unsigned int num = n;
if (n < 0)
{
_putchar('-');
num = -num;
}
if (num / 10)
print_number(num / 10);
_putchar((num % 10) + '0');
}
/**
* print_unsigned_number - Helper function to print an unsigned integer
* @n: The unsigned integer to print
*/
void print_unsigned_number(unsigned int n)
{
if (n / 10)
print_unsigned_number(n / 10);
_putchar((n % 10) + '0');
}
/**
* handle_specifier - Handles a format specifier
* @specifier: The format specifier
* @args: The va_list of arguments
*
* Return: The number of characters printed
*/
int handle_specifier(char specifier, va_list args)
{
char *str;
int count = 0;
char c;
int num;
if (specifier == 'c')
{
c = va_arg(args, int);
count += _putchar(c);
}
else if (specifier == 's')
{
str = va_arg(args, char *);
if (!str)
str = "(null)";
while (*str)
count += _putchar(*str++);
}
else if (specifier == '%')
{
count += _putchar('%');
}
else if (specifier == 'd' || specifier == 'i')
{
num = va_arg(args, int);
print_number(num);
if (num <= 0)
count++;
while (num != 0)
{
count++;
num /= 10;
}
}
else
{
count += _putchar('%');
count += _putchar(specifier);
}
return count;
}
/**
* handle_format - Handles the format string
* @format: The format string
* @args: The va_list of arguments
*
* Return: The number of characters printed
*/
int handle_format(const char *format, va_list args)
{
int i = 0, count = 0;
while (format && format[i])
{
if (format[i] == '%')
{
i++;
if (format[i] == '\0')
return (-1);
count += handle_specifier(format[i], args);
}
else
{
count += _putchar(format[i]);
}
i++;
}
return count;
}
/**
* _printf - Produces output according to a format
* @format: The format string containing the characters and the specifiers
*
* Return: The number of characters printed (excluding the null byte used to
* end output to strings)
*/
int _printf(const char *format, ...)
{
va_list args;
int count;
if (!format)
return (-1);
va_start(args, format);
count = handle_format(format, args);
va_end(args);
return count;
}