-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcd.c
More file actions
111 lines (100 loc) · 1.95 KB
/
cd.c
File metadata and controls
111 lines (100 loc) · 1.95 KB
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
#include "holberton.h"
/**
* _cd - execute cd builtin
* @ssh: input ssh
* Return: 1 on success, 0 on failure
*/
int _cd(_unix *ssh)
{
register uint count = 0;
_Bool ableToChange = false;
count = Arguments(ssh->args);
if (count == 1)
ableToChange = _cdDirectory(ssh);
else if (count == 2 && _strcmp(ssh->args[1], "-") == 0)
ableToChange = _cdBefore(ssh);
else
ableToChange = _cdUser(ssh);
if (ableToChange)
Uenviron(ssh);
return (1);
}
/**
* _cdDirectory - change directory to home
* @ssh: input ssh
* Return: true on success, false on failure
*/
_Bool _cdDirectory(_unix *ssh)
{
register int i;
char *str, *ptr;
i = searchNode(ssh->env, "HOME");
if (i == -1)
{
return (true);
}
str = getNodeAtIndex(ssh->env, i);
ptr = _strchr(str, '=');
ptr++;
chdir(ptr);
free(str);
return (true);
}
/**
* _cdBefore - change directory to previous directory -
* address is found in OLDPWD env var
* @ssh: input ssh
* Return: true on success, false on failure
*/
_Bool _cdBefore(_unix *ssh)
{
register int i;
char *str, *ptr;
char *current = NULL;
current = getcwd(current, 0);
i = searchNode(ssh->env, "OLDPWD");
if (i == -1)
{
chdir(current);
write(STDOUT_FILENO, current, _strlen(current));
displayNewLine();
return (true);
}
str = getNodeAtIndex(ssh->env, i);
ptr = _strchr(str, '=');
ptr++;
chdir(ptr);
write(STDOUT_FILENO, ptr, _strlen(ptr));
displayNewLine();
free(str);
return (true);
}
/**
* _cdUser - change directory to what user inputs in
* @ssh: input ssh
* Return: true on success, false on failure
*/
_Bool _cdUser(_unix *ssh)
{
register int changeStatus;
changeStatus = chdir(ssh->args[1]);
if (changeStatus == -1)
{
errno = HCD;
_getError(ssh);
return (false);
}
return (true);
}
/**
* Uenviron - change environmental variables
* @ssh: input ssh
* Return: true on success false on failure
*/
_Bool Uenviron(_unix *ssh)
{
register int i;
i = uDirectory(ssh);
current(ssh, i);
return (true);
}