-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprintf.c
85 lines (83 loc) · 1.44 KB
/
printf.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
#include "main.h"
/**
* _printf - a function that produces output according to a format
* @format: a string that contains characters
* Return: Returns the number of characters printed
*/
int _printf(const char *format, ...);
int _printf(const char *format, ...)
{
int j, i, len = 0, p;
char *str;
char c;
unsigned int bin;
va_list arg_list;
va_start(arg_list, format);
if (format == NULL || strlen(format) == 1)
return (-1);
for (i = 0; format[i] != '\0'; i++)
{
if (format[i] == '%')
{
i++;
if (format[i] == 'c')
{
c = va_arg(arg_list, int);
_putchar(c);
len++;
}
else if (format[i] == 's')
{
str = va_arg(arg_list, char *);
if (str == NULL)
str = "(null)";
for (j = 0; str[j] != '\0'; j++)
{
_putchar(str[j]);
len++;
}
}
else if (format[i] == '%')
{
_putchar('%');
len++;
}
else if (format[i] == 'd' || format[i] == 'i')
{
p = va_arg(arg_list, int);
str = Itoa(p);
for (j = 0; str[j] != '\0'; j++)
{
_putchar(str[j]);
len++;
}
free(str);
}
else if (format[i] == 'b')
{
bin = va_arg(arg_list, unsigned int);
str = bin_convert(bin);
for (j = 0; str[j] != '\0'; j++)
{
_putchar(str[j]);
len++;
}
free(str);
}
else
{
_putchar('%');
len++;
_putchar(format[i]);
len++;
}
}
else
{
_putchar (format[i]);
len++;
}
}
va_end(arg_list);
return (len);
}