Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
yabtaour
GitHub Repository: yabtaour/Minishell-42
Path: blob/main/execution/my_mess/my_cd.c
1407 views
1
/* ************************************************************************** */
2
/* */
3
/* ::: :::::::: */
4
/* my_cd.c :+: :+: :+: */
5
/* +:+ +:+ +:+ */
6
/* By: ssabbaji <[email protected]> +#+ +:+ +#+ */
7
/* +#+#+#+#+#+ +#+ */
8
/* Created: 2022/08/24 15:42:55 by ssabbaji #+# #+# */
9
/* Updated: 2022/10/07 12:31:00 by ssabbaji ### ########.fr */
10
/* */
11
/* ************************************************************************** */
12
13
#include "../../minishell.h"
14
15
int my_chdir(t_data *data, char *cmd, char *cwd)
16
{
17
char *new_pwd;
18
19
new_pwd = cmd;
20
if (!ft_strcmp(cmd, "-"))
21
return (go_back_minus(data));
22
else
23
g_vars.g_exit_stat = chdir(new_pwd);
24
if (g_vars.g_exit_stat)
25
return (perror("chdir() error:"), 1);
26
else
27
{
28
new_pwd = getcwd(NULL, 256);
29
update_env(data, "OLDPWD", cwd);
30
update_env(data, "PWD", new_pwd);
31
}
32
free(new_pwd);
33
return (g_vars.g_exit_stat);
34
}
35
36
void find_dir(t_data *data, char *pwd, char *upd)
37
{
38
int i;
39
char *test_pwd;
40
41
i = 0;
42
test_pwd = NULL;
43
while (pwd[i])
44
i++;
45
while (pwd[i] != '/')
46
i--;
47
test_pwd = ft_strncpy(test_pwd, pwd, i);
48
if (chdir(test_pwd))
49
find_dir(data, test_pwd, upd);
50
else
51
my_chdir(data, test_pwd, upd);
52
free(test_pwd);
53
}
54
55
int catch_error(t_data *data)
56
{
57
char *old_pwd;
58
59
old_pwd = custom_getenv("PWD", data->lst_env);
60
print_error();
61
g_vars.g_exit_stat = go_home(data, old_pwd);
62
return (g_vars.g_exit_stat);
63
}
64
65
int my_cd(t_data *data, t_cmd *lst_cmd)
66
{
67
char *cwd;
68
char **cmd;
69
int exit_stat;
70
71
cmd = lst_cmd->cmd;
72
cwd = getcwd(NULL, 256);
73
if (cmd[1])
74
{
75
if (!cwd)
76
return (catch_error(data));
77
else
78
exit_stat = my_chdir(data, cmd[1], cwd);
79
}
80
else
81
return (go_home(data, cwd));
82
free(cwd);
83
return (exit_stat);
84
}
85
86