-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.c
121 lines (105 loc) · 1.67 KB
/
errors.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
/*
* File: errors.c
* Auth: Wandile Dlamini
* Lwazi
*/
#include "shell.h"
int num_len(int num);
char *_itoa(int num);
int create_error(char **args, int err);
/**
* num_len - Counts the digit length of a number.
* @num: The number to measure.
*
* Return: The digit length.
*/
int num_len(int num)
{
unsigned int num1;
int len = 1;
if (num < 0)
{
len++;
num1 = num * -1;
}
else
{
num1 = num;
}
while (num1 > 9)
{
len++;
num1 /= 10;
}
return (len);
}
/**
* _itoa - Converts an integer to a string.
* @num: The integer.
*
* Return: The converted string.
*/
char *_itoa(int num)
{
char *buffer;
int len = num_len(num);
unsigned int num1;
buffer = malloc(sizeof(char) * (len + 1));
if (!buffer)
return (NULL);
buffer[len] = '\0';
if (num < 0)
{
num1 = num * -1;
buffer[0] = '-';
}
else
{
num1 = num;
}
len--;
do {
buffer[len] = (num1 % 10) + '0';
num1 /= 10;
len--;
} while (num1 > 0);
return (buffer);
}
/**
* create_error - Writes a custom error message to stderr.
* @args: An array of arguments.
* @err: The error value.
*
* Return: The error value.
*/
int create_error(char **args, int err)
{
char *error;
switch (err)
{
case -1:
error = error_env(args);
break;
case 1:
error = error_1(args);
break;
case 2:
if (*(args[0]) == 'e')
error = error_2_exit(++args);
else if (args[0][0] == ';' || args[0][0] == '&' || args[0][0] == '|')
error = error_2_syntax(args);
else
error = error_2_cd(args);
break;
case 126:
error = error_126(args);
break;
case 127:
error = error_127(args);
break;
}
write(STDERR_FILENO, error, _strlen(error));
if (error)
free(error);
return (err);
}