/
builtins.c
117 lines (101 loc) · 1.89 KB
/
builtins.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
#include "holberton.h"
/**
* changedir - changes working directory to user entered path
* @p: pointer to user entered commands
* @predirect: the previous directory
* Return: 1 if successful
*/
int changedir(char **p, CHDIRECT *predirect)
{
char cd[] = "cd";
char tilde[] = "~";
char dash[] = "-";
char *s;
char *temp;
if (_strcmp(p[0], cd) == 0)
{
predirect->boo = 1;
if (p[1] == NULL || _strcmp(p[1], tilde) == 0)
{
s = _getenv("HOME");
free(predirect->s);
predirect->s = _strdup(_getenv("PWD"));
chdir(s);
}
else if (_strcmp(p[1], dash) == 0)
{
temp = _strdup(_getenv("PWD"));
chdir(predirect->s);
write(STDOUT_FILENO, predirect->s, _strlen(predirect->s));
write(STDOUT_FILENO, "\n", 1);
free(predirect->s);
predirect->s = temp;
}
else
{
temp = _strdup(_getenv("PWD"));
if (chdir(p[1]) == -1)
{
free(temp);
return (-1);
}
else
{
free(predirect->s);
predirect->s = temp;
}
}
}
return (0);
}
/**
* *_getenv - returns an environmental variable value
* @name: key to access the env value
* Return: pointer to the value
*/
char *_getenv(const char *name)
{
int i = 0, j, len = 0;
if (!name)
{
return (NULL);
}
else
{
while (name[len] != '\0')
len++;
}
while (environ[i])
{
for (j = 0; j < len && *(environ[i] + j) != '\0'; j++)
{
if (name[j] != *(environ[i] + j))
break;
if (j == len - 1)
return (environ[i] + j + 2);
}
i++;
}
return (NULL);
}
/**
* checkenv - checks to see if the token is the env
* @p: user supplies command line arguments
* Return: returns 1 if user entered the command; zero otherwise
*/
int checkenv(char **p)
{
char command[] = "env";
int i = 0;
if (_strcmp(*p, command) == 0)
{
while (environ[i])
{
write(STDOUT_FILENO, environ[i], _strlen(environ[i]));
write(STDOUT_FILENO, "\n", 1);
i++;
}
return (1);
}
return (0);
}