-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchdir.c
50 lines (49 loc) · 1001 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
#include "main.h"
/**
* _chdir - implements cd builtin
* @dir_name: name of destination directory
* @av: program command
* Return: 0 or -1
*/
int _chdir(char *dir_name, char *av)
{
char *old = get_env("OLDPWD"), *present = get_env("PWD");
char *current = malloc(sizeof(char) * 1024), *home = get_env("HOME");
size_t cur_size = 1024;
int ret;
if (!dir_name)
{
chdir(home);
getcwd(current, cur_size);
setenv("OLDPWD", present, 1);
setenv("PWD", current, 1);
free(current);
return (0);
}
if (str_cmp(dir_name, "-") == 0)
{
chdir(old);
getcwd(current, cur_size);
_puts(current);
_puts("\n");
setenv("OLDPWD", present, 1);
setenv("PWD", current, 1);
free(current);
return (0);
}
ret = chdir(dir_name);
if (ret < 0)
{
p_error(av);
p_error(": 1: cd: can't cd to ");
p_error(dir_name);
p_error("\n");
free(current);
return (-1);
}
getcwd(current, cur_size);
setenv("OLDPWD", present, 1);
setenv("PWD", current, 1);
free(current);
return (0);
}