-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubstitution.c
87 lines (84 loc) · 1.82 KB
/
substitution.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
#include "shell.h"
/**
* handleSubstitution - Handles variable substitution
*
* @token: A pointer to a part of the command line
* @status: The last command's exist status
*
* Return: A pointer to the (possibly edited) command line
*/
char *handleSubstitution(char *token, int status)
{
char pidString[10], statusString[10], *varValue, *modifiedToken = NULL;
int i = 0, statusCopy = status;
pid_t pid = getpid();
if (token[0] == '$')
{
if (myCustomStrcmp(token, "$$") == 0)
{
intToStr(pidString, pid, i);
modifiedToken = myCustomStrdup(pidString);
return (modifiedToken);
}
else if (myCustomStrcmp(token, "$?") == 0)
{
if (status == 0)
return (myCustomStrdup("0"));
else if (status > 0)
{
intToStr(statusString, statusCopy, i);
modifiedToken = myCustomStrdup(statusString);
return (modifiedToken);
}
else
{
statusString[i++] = '-';
statusCopy *= -1;
intToStr(statusString, statusCopy, i);
modifiedToken = myCustomStrdup(statusString);
return (modifiedToken);
}
}
else
{
varValue = myCustomGetenv(token + 1);
if (varValue != NULL)
modifiedToken = myCustomStrdup(varValue);
}
}
return (modifiedToken);
}
/**
* reverseString - Reverses a string
*
* @string: a pointer to a string
*/
void reverseString(char *string)
{
size_t length = myCustomStrlen(string);
int i, j;
char temp;
for (i = 0, j = length - 1; i < j; i++, j--)
{
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
/**
* intToStr - Converts a number to a string
*
* @string: A pointer to a numeral string
* @number: A number
* @index: The index to start placing characters
*/
void intToStr(char *string, int number, int index)
{
while (number > 0)
{
string[index++] = (number % 10) + '0';
number /= 10;
}
string[index] = '\0';
reverseString(string);
}