-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcd.c
48 lines (47 loc) · 1.18 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
#include "cd.h"
#include "headers.h"
int cd(char* path){
extern char homedir[PATH_MAX];
extern char prevDir[PATH_MAX];
/*
* If Dir starts with ~ changw ith respect to homedir
*
*/
if('-'==path[0]){
if(strlen(path)>1){
printf("'-' with extra path is not supported. Aborting..\n");
}else{
if(prevDir[0]){
printf("%s\n", prevDir);
cd(prevDir);
}else
printf("Directory not changed yet.\n");
}
}else if('~'==path[0]){
int i=0, j=1;
char npath[strlen(homedir)+strlen(path)];
while(homedir[i]){
npath[i]=homedir[i];
i++;
}
while(path[j]){
npath[i]=path[j];
i++;
j++;
}
npath[i]='\0';
cd(npath);
}else if(chdir(path)==-1){
if(errno==ENOENT)
printf("Path Doesn't Exist\n");
else if(errno==ENOTDIR)
printf("A component is Not Dir\n");
else if(errno==EACCES)
printf("Permission Denied\n");
else
perror("Error: ");
return -1;
}else{
return 0;
}
}