-
Notifications
You must be signed in to change notification settings - Fork 1
/
cd.c
70 lines (66 loc) · 1.25 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
#include "shell.h"
/**
* fnd_path - This function returns path
* @str: Variable name
*
* Return: Value stored in a variable
*/
char *fnd_path(char *str)
{
int i;
char *path = NULL;
char *temp = NULL;
char *allpath = NULL;
i = find_var(str, enviroment);
if (i == -1)
return (NULL);
path = malloc(sizeof(char) * (_strlen(enviroment[i]) + 2));
path = _strcpy(path, enviroment[i]);
temp = path;
for (i = 0; *path != '='; i++)
path++;
path++;
allpath = malloc(sizeof(char) * (_strlen(path) + 2));
allpath = _strcpy(allpath, path);
free(temp);
return (allpath);
}
/**
* cd - Change current working directory
* @argv: Arguments
*/
void cd(char **argv)
{
int i;
char *path = NULL;
char *oldpwd = NULL;
if (argv[1] == NULL)
{
path = fnd_path("HOME");
if (!path)
path = fnd_path("PWD");
}
else if (argv[1][0] == '-')
{
path = fnd_path("OLDPWD");
if (path == NULL)
path = fnd_path("PWD");
_printf("%s\n", path);
}
else
{
path = malloc(sizeof(char) * _strlen(argv[1]) + 2);
path = _strcpy(path, argv[1]);
}
i = chdir(path);
if (i == -1)
{
fprintf(stderr, "./hsh: 1: cd: can't cd to %s\n", argv[1]);
return;
}
oldpwd = fnd_path("PWD");
setenv("PWD", path, 1);
free(path);
setenv("OLDPWD", oldpwd, 1);
free(oldpwd);
}