-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcd.c
113 lines (108 loc) · 2.1 KB
/
cd.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
#include "shell.h"
/**
* implementCdCommand - Implements the cd built-in command
*
* @tokens: An array of command line strings
* @argv: An array of command line arguments
*/
void implementCdCommand(char **tokens, char **argv)
{
char currentDirectory[1024];
if (tokens[1] == NULL) /*If cd has no arguments*/
{
cdNoArgument();
}
else if (myCustomStrcmp(tokens[1], "-") == 0) /*If "cd -" is used*/
{
handleCdDash();
}
else if (myCustomStrcmp(tokens[1], "/root") == 0) /*If cd /root is used*/
{
printCdError(argv[0], tokens[1]);
}
else /*If any other path is used with cd*/
{
setOldPwd();
if (chdir(tokens[1]) != 0)
printCdError(argv[0], tokens[1]);
else
{
if (getcwd(currentDirectory, sizeof(currentDirectory)) == NULL)
perror("getcwd");
if (myCustomSetenv("PWD", currentDirectory, 1) != 0)
perror("setenv");
}
}
}
/**
* setOldPwd - Sets OLDPWD variable
*/
void setOldPwd(void)
{
char previousDirectory[1024];
if (getcwd(previousDirectory, sizeof(previousDirectory)) == NULL)
{
perror("getcwd");
}
else
{
if (myCustomSetenv("OLDPWD", previousDirectory, 1) != 0)
{
perror("setenv");
}
}
}
/**
* cdNoArgument - Handles cd with no argument
*/
void cdNoArgument(void)
{
char *home;
home = myCustomGetenv("HOME");
if (home != NULL)
{
setOldPwd();
if (chdir(home) != 0)
{
perror("cd");
}
else
{
if (myCustomSetenv("PWD", home, 1) != 0)
{
perror("setenv");
}
}
}
else
{
setOldPwd();
}
}
/**
* handleCdDash - Handles cd with '-' as an argument
*/
void handleCdDash(void)
{
char currentDirectory[1024];
if (myCustomGetenv("OLDPWD") == NULL)
{
write(STDOUT_FILENO, myCustomGetenv("PWD"),
myCustomStrlen(myCustomGetenv("PWD")));
write(STDOUT_FILENO, "\n", 1);
}
else
{
if (chdir(myCustomGetenv("OLDPWD")) != 0)
perror("cd");
else
{
if (getcwd(currentDirectory, sizeof(currentDirectory)) == NULL)
perror("getcwd");
if (myCustomSetenv("PWD", currentDirectory, 1) != 0)
perror("setenv");
write(STDOUT_FILENO, currentDirectory, myCustomStrlen(currentDirectory));
write(STDOUT_FILENO, "\n", 1);
}
}
}