-
Notifications
You must be signed in to change notification settings - Fork 0
/
cd.c
70 lines (65 loc) · 1.33 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
#include "shell.h"
/**
* cd - changes the current working directory
* @args: arguments
*/
void my_cd(char **args)
{
char **directories = NULL, *oldpwd = NULL, *home = NULL;
if (args[1] == NULL)
{
home = _getenv("HOME");
if (home == NULL)
{
write(STDERR_FILENO, "cd: HOME not set\n", 17);
return;
}
directories = malloc(sizeof(char *) * 2);
if (directories == NULL)
return;
directories[0] = home;
directories[1] = NULL;
}
else if (_strncmp(args[1], "-", 1) == 0)
{
oldpwd = _getenv("OLDPWD");
if (oldpwd == NULL)
{
write(STDERR_FILENO, "cd: OLDPWD not set\n", 19);
return;
}
directories = malloc(sizeof(char *) * 2);
if (directories == NULL)
return;
directories[0] = oldpwd;
directories[1] = NULL;
}
else
{
directories = malloc(sizeof(char *) * 2);
if (directories == NULL)
return;
directories[0] = args[1];
directories[1] = NULL;
}
change_directory(directories, args[0]);
free(directories);
}
/**
* change_directory - changes the current working directory
* @directories: directories to change to
* @command_name: name of the command
*/
void change_directory(char **directories, char *command_name)
{
char *pwd = getcwd(NULL, 0);
if (chdir(directories[0]) == -1)
{
print_error(command_name, 0, directories[0], "can't cd to ");
return;
}
else
{
free(pwd);
}
}