-
Notifications
You must be signed in to change notification settings - Fork 0
/
_cd_.c
94 lines (90 loc) · 2.34 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
#include "main.h"
/**
* _cd_ - changes the current directory of the process.
* @parse: the command to be checked.
*
* Return: void.
*/
void _cd_(char **parse)
{
char **ptr = parse, *path;
int len_parse = 0, res;
/* Changes the current directory of the process */
while (ptr[len_parse] != NULL)
len_parse++;
if (len_parse == 1)
path = _getenv("HOME"); /* cd $HOME */
else if (len_parse == 2)
{
if (_strcmp(parse[1], "-") == 0)
path = _getenv("OLDPWD"); /* cd - */
else
path = parse[1]; /* cd [DIRECTORY] */
}
else
{
logical_counter = 1; /* Command fails */
exit_status = 2;
_cd_error(parse[1]);
}
if (len_parse <= 2)
{
res = chdir(path);
if (res != 0)
{
logical_counter = 1; /* Command fails */
exit_status = 2;
_cd_error(parse[1]);
}
logical_counter = 0; /* Command succeeds */
/*Update the environment variables when directory was changed*/
_update_env(path);
}
}
/**
* _update_env - updates the environment variables when directory was changed.
* @path: the directory to be added.
*
* return: void.
*/
void _update_env(char *path)
{
char *oldpwd_value, *pwd_value, *pwd_path, **env = environ;
int oldpwd_pos = 0, pwd_pos = 0, pwd_path_size;
struct stat st;
oldpwd_value = _getenv("OLDPWD");
if (oldpwd_value == NULL)
_print("Error: OLDPWD value not found\n");
pwd_value = _getenv("PWD");
if (pwd_value == NULL)
_print("Error: PWD value not found\n");
while (_strncmp(env[oldpwd_pos], "OLDPWD", 6) != 0)
oldpwd_pos++;
while (_strncmp(env[pwd_pos], "PWD", 3) != 0)
pwd_pos++;
/* -- Updates OLDPWD -- */
env[oldpwd_pos] = _realloc(env[oldpwd_pos],
_strlen(oldpwd_value) + 8, _strlen(pwd_value) + 8);
if (env[oldpwd_pos] == NULL)
perror("Error: realloc\n");
_snprint(env[oldpwd_pos], _strlen(pwd_value) + 8, "OLDPWD",
pwd_value);
/* -- Updates PWD -- */
pwd_path_size = _strlen(pwd_value) + _strlen(path) + 2;
pwd_path = malloc(sizeof(pwd_path) * pwd_path_size);
if (pwd_path == NULL)
perror("Error: malloc\n");
if (getcwd(pwd_path, sizeof(pwd_path) * pwd_path_size) == NULL)
perror("Error: getcwd()");
if (stat(pwd_path, &st) == 0)
{
env[pwd_pos] = _realloc(env[pwd_pos],
_strlen(pwd_value) + 5, _strlen(pwd_path) + 5);
if (env[pwd_pos] == NULL)
perror("Error: realloc\n");
_snprint(env[pwd_pos], _strlen(pwd_path) + 5, "PWD",
pwd_path);
}
else
perror("Error: stat");
}