-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcd_function.c
More file actions
55 lines (50 loc) · 1.11 KB
/
cd_function.c
File metadata and controls
55 lines (50 loc) · 1.11 KB
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
/*
** EPITECH PROJECT, 2025
** B-PSU-200-LYN-2-1-minishell1-pierre.baud
** File description:
** cd_function
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "my.h"
char *get_home_directory(char **envc)
{
char *token;
char *home_dir;
char *env_copy;
int i = 0;
for (; envc[i] != NULL; i++) {
env_copy = my_strdup(envc[i]);
token = strtok(env_copy, "=");
if (token != NULL && my_strcmp(token, "HOME") == 0) {
token = strtok(NULL, "=");
home_dir = my_strdup(token);
free(env_copy);
return home_dir;
}
free(env_copy);
}
return NULL;
}
int my_cd(char **args, char **envc, int *built_in_st)
{
char *home;
if (args[1] == NULL) {
home = get_home_directory(envc);
if (home == NULL) {
*built_in_st = 1;
}
if (chdir(home) != 0) {
perror("cd");
*built_in_st = 1;
}
} else {
if (chdir(args[1]) != 0) {
perror("cd");
*built_in_st = 1;
}
}
return 0;
}