-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcd.c
49 lines (47 loc) · 1.07 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
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc, char const *argv[]) {
char *path;
char *new_path;
int save_errno;
if (argc > 2) {
printf("Program CD.\nDescription: change current directory.\nUsage: cd [<dir>]\n");
exit(EXIT_FAILURE);
}
path = (char *) malloc(PATH_MAX);
new_path = (char *) malloc(PATH_MAX);
if (!path || !new_path) {
printf("malloc error\n");
exit(EXIT_FAILURE);
}
if (getcwd(path, PATH_MAX) == NULL) {
save_errno = errno;
printf("Error: %s\n",strerror(save_errno));
exit(EXIT_FAILURE);
}
if (argc == 1) {
printf("%s\n",path);
return 0;
}
if (realpath(argv[1],new_path) == NULL) {
save_errno = errno;
printf("Error: %s\n",strerror(save_errno));
exit(EXIT_FAILURE);
}
if (chdir(new_path)) {
save_errno = errno;
printf("Error: %s\n",strerror(save_errno));
exit(EXIT_FAILURE);
}
if (getcwd(path, PATH_MAX) == NULL) {
save_errno = errno;
printf("Error: %s\n",strerror(save_errno));
exit(EXIT_FAILURE);
}
printf("%s\n",path);
return 0;
}