-
Notifications
You must be signed in to change notification settings - Fork 0
/
cdir.c
100 lines (94 loc) · 1.86 KB
/
cdir.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
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
#include "shell.h"
/**
* wcount - counts the number of words in a string
* @str: string to count words in
* @delim: delimeters separating words
*
* Return: Number of words in string, -1 on failure
*/
int wcount(char *str, char *delim)
{
int count;
char *dup;
dup = str;
if (str == NULL)
{
perror("Invalid String");
return (-1);
}
strtok(dup, delim);
for (count = 1; strtok(NULL, delim) != NULL; count++)
;
return (count);
}
/**
* change_dir - changes current working directory and updates OLDPWD
* @cmd: command to change working directory
*
* Return: 0 if successful, -1 otherwise
*/
int change_dir(char *cmd)
{
char *path, *oldpwd, *pwd, *dup, buf[256];
int words;
size_t size = 256;
dup = _strdup(cmd);
words = wcount(dup, " \t\r");
if (words > 2)
{
_perror(cmd, "too many arguments");
free(dup);
dup = NULL;
return (-1);
}
strtok(cmd, " \t\r");
path = strtok(NULL, " ");
if (path == NULL) /* home directory */
{
oldpwd = getcwd(buf, size);
chdir(_getenv("HOME"));
setenv("OLDPWD", oldpwd, 1);
setenv("PWD", _getenv("PWD"), 1);
free(dup);
dup = NULL;
return (0);
}
if (_strcmp(path, "-") == 0)
{
if (_getenv("OLDPWD") == NULL)
{
perror("OLDPWD"); /* OLDPWD not net */
free(dup);
dup = NULL;
return (-1);
}
else
{
oldpwd = getcwd(buf, size);
chdir(_getenv("OLDPWD"));
setenv("OLDPWD", oldpwd, 1); /* Update OLDPWD */
pwd = getcwd(buf, size);
setenv("PWD", pwd, 1);
free(dup);
dup = NULL;
return (0);
}
}
oldpwd = getcwd(buf, size);
if (chdir(path) == -1)
{
print_error(_getenv("_"));
print_error(": 1: cd: can't cd to ");
write(STDERR_FILENO, path, _strlen(path));
print_error("\n");
free(dup);
dup = NULL;
return (-1);
}
setenv("OLDPWD", oldpwd, 1); /* Update OLDPWD */
pwd = getcwd(buf, size);
setenv("PWD", pwd, 1);
free(dup);
dup = NULL;
return (0);
}