-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuiltin.c
62 lines (58 loc) · 1.44 KB
/
builtin.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 "builtin.h"
#include "utils.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
// returns true if "chdir" was performed
// this means that if 'cmd' contains:
// 1. $ cd directory (change to 'directory')
// 2. $ cd (change to HOME)
// it has to be executed and then return true
// Remember to update the 'prompt' with the
// new directory.
//
// Examples:
// 1. cmd = ['c','d', ' ', '/', 'b', 'i', 'n', '\0']
// 2. cmd = ['c','d', '\0']
int cd(char *cmd) {
char *home = getenv("HOME");
char aux_cmd[strlen(cmd)];
strcpy(aux_cmd, cmd);
// we know that cd is follow by space so we split and righ side is our
// directory
char *directory = split_line(aux_cmd, ' ');
char *prefix = "~/";
char *new_prompt;
if (strcmp(aux_cmd, "cd") == 0) {
if (strlen(directory) != 0) {
if (chdir(directory) != 0) {
printf("cd: %s: directory does not exist\n", directory);
} else {
new_prompt = (char *)malloc(strlen(directory + 2));
strcpy(new_prompt, prefix);
strcat(new_prompt, directory);
strcpy(prompt, new_prompt);
free(new_prompt);
}
} else {
chdir(home);
strcpy(home, prompt);
}
return true;
}
return 0;
}
int exit_shell(char *cmd) {
if (strcmp(cmd, "exit") == 0) {
return true;
}
return 0;
}
int exec_jobs(char *cmd) {
if (strcmp(cmd, "jobs") == 0) {
return true;
}
return 0;
}