-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathms_cd.c
91 lines (83 loc) · 2.48 KB
/
ms_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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ms_cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: siychoi <siychoi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/06 15:35:28 by siychoi #+# #+# */
/* Updated: 2024/07/01 15:26:29 by siychoi ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static int print_cd_error(char *str, int error_type);
static int ms_cd_no_options(t_envp **my_envp, char *old_pwd);
void ms_cd2(t_envp **my_envp, char *argv[], char *pwd, int *status);
int ms_cd(t_envp **my_envp, char **argv)
{
int status;
char *pwd;
status = 0;
pwd = getcwd(NULL, 0);
if (argv[1] == NULL || (argv[1][0] == '~' && argv[1][1] == '\0'))
{
free_2d_array(argv);
return (ms_cd_no_options(my_envp, pwd));
}
if (argv[1][0] == '-' && argv[1][1] != '\0')
{
free(pwd);
free_2d_array(argv);
return (print_cd_error(NULL, 1));
}
ms_cd2(my_envp, argv, pwd, &status);
free_2d_array(argv);
return (status);
}
void ms_cd2(t_envp **my_envp, char *argv[], char *pwd, int *status)
{
if (chdir(argv[1]) == -1)
{
print_code_error_builtin(errno, argv[0]);
*status = 1;
free(pwd);
}
else
{
change_value(my_envp, "OLDPWD", pwd);
change_value(my_envp, "PWD", getcwd(NULL, 0));
}
}
static int ms_cd_no_options(t_envp **my_envp, char *old_pwd)
{
char *home_path;
home_path = find_value(my_envp, "HOME");
if (chdir(home_path) == -1)
{
ft_putstr_fd("minishell : cd: HOME not set\n", 2);
free(old_pwd);
free(home_path);
return (1);
}
else
{
change_value(my_envp, "OLDPWD", old_pwd);
change_value(my_envp, "PWD", getcwd(NULL, 0));
}
free(home_path);
return (0);
}
static int print_cd_error(char *str, int error_type)
{
if (error_type == 1)
{
ft_putstr_fd("minishell: cd: can't have options\n", 2);
}
else if (error_type == 2)
{
ft_putstr_fd("minishell: cd: ", 2);
ft_putstr_fd(str, 2);
ft_putstr_fd(": No such file or directory\n", 2);
}
return (1);
}