-
Notifications
You must be signed in to change notification settings - Fork 1
/
_chdir.c
53 lines (51 loc) · 819 Bytes
/
_chdir.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
#include "main.h"
/**
* _chdir - changes directory
* @arguments: args
* Return: 1 else 0
*/
int _chdir(char **arguments)
{
char *c_dir = getcwd(NULL, 0);
char *p_dir = getenv("OLDPWD");
const char *_home = getenv("HOME");
if (arguments[1] == NULL)
{
if (_home != 0)
{
perror("cd");
}
}
else if (_strcmp(arguments[1], "-") == 0)
{
if (p_dir == NULL)
{
fprintf(stderr, "cd: OLDPWD not set\n");
}
else
{
if (chdir(p_dir) != 0)
{
perror("cd");
}
write(STDOUT_FILENO, p_dir, _strlen(p_dir));
write(STDOUT_FILENO, "\n", 1);
}
}
else
{
if (chdir(arguments[1]) != 0)
{
perror("cd");
}
}
if (c_dir == NULL)
{
perror("cd: getcwd error");
exit(EXIT_FAILURE);
}
setenv("OLDPWD", getenv("PWD"), 1);
setenv("PWD", c_dir, 1);
free(c_dir);
return (1);
}