maxishell
Implementation of a shell for Linux-like systems
Loading...
Searching...
No Matches
cd.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* cd.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: dmdemirk <dmdemirk@student.42london.c +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2024/06/03 16:31:07 by dmdemirk #+# #+# */
9/* Updated: 2024/09/09 13:09:59 by dmdemirk ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include <stdio.h>
14#include "libft.h"
15#include "shell.h"
16#include "env.h"
17#include "execute.h"
18#include "exit_status.h"
19
20/*
21 - Functionality:
22 - Change the current directory
23 - Update the PWD and OLDPWD environment variables
24 - If no argument is provided, change to the HOME directory
25 - If the target directory does not exist, print an error message
26 */
27
29{
30 char *target_dir;
31 char *home_dir;
32 char *error_message;
33 char cwd[4096];
34
35 home_dir = get_env(data->envp, "HOME");
36 target_dir = (char *)data->args[1];
37 if (!target_dir)
38 target_dir = home_dir;
39 if (chdir(target_dir) == -1)
40 {
41 error_message = ft_strjoin("cd: ", target_dir);
42 if (errno == EACCES)
43 exit_status_handler(data, PERMISSION_DENIED, error_message);
44 if (errno == ENOENT)
45 exit_status_handler(data, IS_DIRECTORY, error_message);
46 free(error_message);
47 return (EXIT_FAILURE);
48 }
49 set_env(&data->envp, "OLDPWD", get_env(data->envp, "PWD"));
50 if (getcwd(cwd, sizeof(cwd)) != NULL)
51 set_env(&data->envp, "PWD", cwd);
52 return (EXIT_SUCCESS);
53}
int builtin_cd(t_ms_data *data)
Definition cd.c:28
void set_env(t_env **env, const char *key, const char *value)
Definition env.c:73
char * get_env(t_env *envp, const char *key)
Definition env.c:59
#define EXIT_SUCCESS
Definition exit_status.h:16
#define EXIT_FAILURE
Definition exit_status.h:17
#define PERMISSION_DENIED
Definition exit_status.h:25
void exit_status_handler(t_ms_data *data, int status_code, char *err_arg)
Definition exit_status.c:25
#define IS_DIRECTORY
Definition exit_status.h:20
char * ft_strjoin(char const *s1, char const *s2)
Definition ft_strjoin.c:23
t_env * envp
Definition shell.h:24
char ** args
Definition shell.h:23