-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcd.c
69 lines (62 loc) · 1.4 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
#include "includes.h"
#include "types.h"
#include "utils.h"
#include "constants.h"
#include "getcwd.h"
// variable name same as BASH
// working directory originally home
char oldpwd[MAX_PATH_LEN] = "~";
void cd(command cmd)
{
int prev_dir_flag = 0;
char new_path[MAX_PATH_LEN];
if (cmd.num_args == 1)
{
// no path given, so
// go to home
strcpy(new_path, SHELL_HOME_PATH);
}
else if (cmd.num_args == 2)
{
if (strcmp(cmd.args[1], "-") == 0)
{
// go to previous working directory
strcpy(new_path, oldpwd);
// set flag to print later
prev_dir_flag = 1;
}
else
{
strcpy(new_path, cmd.args[1]);
}
replace_tilde_with_home(new_path);
}
else
{
fprintf(stderr, "Usage: cd <path>\n");
exit(EXIT_FAILURE);
return;
}
// store absolute path of present directory
char *cwd = getcwd(NULL, 0);
// change into new directory
if (chdir(new_path) != 0)
{
printf("%s\n", new_path);
perror("Error while changing directory");
free(cwd);
return;
}
else
{
// store previous directory path
strcpy(oldpwd, cwd);
}
if (prev_dir_flag)
{
// print absolute pathname of new
// directory since "-" was used
pwd(cmd);
}
free(cwd);
}