-
Notifications
You must be signed in to change notification settings - Fork 0
/
cd.c
62 lines (60 loc) · 1.22 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
#include "header.h"
char prev[1000];
int cd(int numPar, char *par[], char home_dir[])
{
if (numPar > 1)
{
perror(" Too many arguments");
return -1;
};
if (numPar == 0)
{
int ret = chdir(home_dir);
if (ret < 0)
{
perror("cd");
return -1;
}
return 1;
}
char path[100000], temp[100000];
strcpy(path, par[0]);
// printf("%s\n", path);
if (path[0] == '~')
{
strcpy(temp, home_dir);
int pathln = strlen(path);
int homeln = strlen(home_dir);
for (int i = 1; i < pathln; i++)
{
temp[homeln + i - 1] = path[i];
}
temp[homeln + pathln - 1] = '\0';
// printf("%s\n", temp);
strcpy(path, temp);
int valid = chdir(path);
if (valid < 0)
{
perror("cd");
return -1;
}
return 1;
}
if (strcmp("-", par[0]) == 0)
{
strcpy(path, prev);
printf("%s\n", path);
}
getcwd(prev, sizeof(prev));
int valid = chdir(path);
if (valid < 0)
{
perror("cd");
return -1;
}
return 1;
}
void cdInit(char homeDir[])
{
strcpy(prev, homeDir);
}