-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinterror.c
127 lines (115 loc) · 2.12 KB
/
printerror.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
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include "main.h"
/**
* _putchar2 - writes the character c to stderr
* @c: The character to print
*
* Return: On success 1.
* On error, -1 is returned, and errno is set appropriately.
*/
int _putchar2(char c)
{
return (write(2, &c, 1));
}
/**
* recursive_int2 - prints the integer to stderr
* @n: the number to be printed
*
* Return: number of numbers printed
*/
int recursive_int2(int n)
{
int n1;
int count = 0;
if (n < 0)
{
n1 = -n;
_putchar2('-');
count++;
}
else
n1 = n;
count++;
if (n1 / 10)
{
count = count + recursive_int2(n1 / 10);
}
_putchar2('0' + (n1 % 10));
return (count);
}
/**
* _printfint2 - handles the cases of %d, %i specifiers to be printed in stderr
* @args: The specific argument
*
* Return: number of integers printed
*/
int _printfint2(va_list args)
{
int d, sum;
d = va_arg(args, int);
sum = recursive_int2(d);
return (sum);
}
/**
* _printfstring2 - handles the cases of %s specifier
* @args: the argument used
*
* Return: length of the string
*/
int _printfstring2(va_list args)
{
char *s;
s = va_arg(args, char *);
if (s == NULL)
{
write(2, "(null)", 6);
return (_strlen("(null)"));
}
write(2, s, strlen(s));
return (strlen(s));
}
/**
* _printferror - takes a formatted string as input to produce output.
* @format: formatted string, may or may not have placeholders.
*
* Return: returns the number of characters printed.
*/
int _printferror(const char *format, ...)
{
int i, j, flag, sum;
va_list arg;
int (*ptr)(va_list);
print_fun f[] = {
{"%s", _printfstring2},
{"%d", _printfint2}
};
va_start(arg, format);
if (format == NULL || (format[0] == '%' && format[1] == '\0'))
return (-1);
for (i = 0, sum = 0; format[i]; i++)
{
flag = 0;
for (j = 0; j < 2; j++)
{
if (format[i] == f[j].form[0] && format[i + 1] == f[j].form[1])
{
ptr = f[j].f;
sum += ptr(arg);
i++;
flag = 1;
break;
}
}
if (flag == 1)
continue;
if (format[i] == '%' && format[i + 1] == '%')
i++;
_putchar2(format[i]);
sum++;
}
va_end(arg);
return (sum);
}