-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcd.c
More file actions
104 lines (93 loc) · 2.14 KB
/
cd.c
File metadata and controls
104 lines (93 loc) · 2.14 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "shell.h"
/**
* get_cwd - get current working directory
*
* Return: pointer to character
* containing current directrory path
*/
char *get_cwd(void)
{
size_t buff_size = 256;
char *temp_dir, *cur_dir;
temp_dir = malloc(sizeof(char) * buff_size);
while (1)
{
getcwd(temp_dir, buff_size);
if (temp_dir == NULL)
{
buff_size *= 2;
if (realloc(temp_dir, (buff_size * sizeof(char))) == NULL)
{
perror("./hsh");
return (NULL);
}
continue;
} else
break;
}
cur_dir = _strdup(temp_dir);
free(temp_dir);
return (cur_dir);
}
/**
* perr - prints error message
* @shellf: shell info
*/
void perr(shell_info shellf)
{
char *loop;
loop = _itoa(shellf.loop_count);
write(STDERR_FILENO, shellf.name, _strlen(shellf.name));
write(STDERR_FILENO, ": ", 2);
write(STDERR_FILENO, loop, _strlen(loop));
write(STDERR_FILENO, ": cd: can't cd to ", 18);
write(STDERR_FILENO, shellf.args[1], _strlen(shellf.args[1]));
write(STDERR_FILENO, "\n", 1);
free(loop);
}
/**
* cd - changes working directory
* @shellf: shell info
*
* Return: 1 if sucessfull
*/
int cd(shell_info __attribute__((unused)) shellf)
{
char *home, *pwd, *oldpwd, *temp_path;
pwd = _getenv("PWD");
oldpwd = _getenv("OLDPWD");
home = _getenv("HOME");
if (!pwd || !oldpwd || !home)
return (-1);
if (shellf.args[1] == NULL || !(_strcmp(shellf.args[1], "~")))
{
chdir(home);
setenv("PWD", home, 1), setenv("OLDPWD", pwd, 1);
free(home), free(pwd), free(oldpwd);
return (1);
}
if (_strcmp(shellf.args[1], "-") == 0)
{
chdir(oldpwd);
write(STDOUT_FILENO, oldpwd, _strlen(oldpwd));
write(STDOUT_FILENO, "\n", 1);
setenv("PWD", oldpwd, 1), setenv("OLDPWD", pwd, 1);
free(home), free(pwd), free(oldpwd);
return (1);
}
temp_path = malloc(sizeof(char) * (_strlen(shellf.args[1]) + 2));
_strcpy(temp_path, shellf.args[1]), _strcat(temp_path, "/");
if (chdir(shellf.args[1]) == 0)
{
setenv("PWD", shellf.args[1], 1);
setenv("OLDPWD", pwd, 1);
} else
{
if (errno == EACCES || errno == ENOENT)
perr(shellf);
else
write(STDERR_FILENO, "not found\n", 10);
}
free(home), free(pwd), free(oldpwd), free(temp_path);
return (-1);
}