-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcd.c
77 lines (73 loc) · 1.57 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "headers.h"
int cd()
{
char *path = malloc(PATH_MAX);
char *pathcpy = malloc(PATH_MAX);
static char *previous_directory = shell_path;
char *arg = malloc(4096);
//get current path
if (getcwd(path, PATH_MAX) == 0)
{
perror("getcwd");
return 1;
}
//make a copy
strcpy(pathcpy, path);
//case when too many arguments
if (arglength > 2)
{
printf("Error:cd too many argument\n");
free(path);
return 1;
}
//no argument given then switch to home directory
if (arglength == 1)
{
strcpy(arg, "~");
}
else
{
//change to current directory only
strcpy(arg, arguments[1]);
}
if (strcmp(arg,".")==0)
{
free(path);
return 0;
}
//switch to home directory
else if (strcmp(arg, "~") == 0)
{
if (chdir(shell_path) == -1)
{
perror("chdir");
free(path);
return 1;
}
}
//switch to previous directory and print
else if (strcmp(arg, "-") == 0)
{
printf("%s\n", previous_directory);
if (chdir(previous_directory) == -1)
{
perror("chdir");
free(path);
return 1;
}
}
else
{ // change to directory token
//manages .. too
if (chdir(arg) == -1)
{
perror("chdir");
free(path);
return -1;
}
}
//retain previous directory path for future use
previous_directory = pathcpy;
free(path);
return 0;
}