-
Notifications
You must be signed in to change notification settings - Fork 1
/
builtins.c
126 lines (108 loc) · 1.38 KB
/
builtins.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include "main.h"
/**
* printenv - prints current environment
* Return: none
*/
void printenv(void)
{
int i = 0;
char **env = environ;
for (i = 0; env[i] != NULL; i++)
{
write(STDOUT_FILENO, env[i], _strlen(env[i]));
}
}
/**
* contains_builtin - check if a builtin command was entered
* @arg: command
* Return: 1 or 0
*/
int contains_builtin(char **arg)
{
int i;
char *argp = (char *) arg;
char *builtins[] = {
"cd",
"env",
"exit"
};
for (i = 0; i < 3; i++)
{
if (argp == builtins[i])
{
return (1);
}
else
{
return (0);
}
}
return (-1);
}
/**
* path_exists - checks if a path exists
* @path: path
* Return: 1 or 0
*/
int path_exists(char *path)
{
struct stat info;
if (stat(path, &info) != -1)
{
return (1);
}
else
{
return (0);
}
}
/**
* cd - changes a working directory
* @args: directory
* Return: none
*/
void cd(char **args)
{
char *arg = (char *) args;
if (!args)
{
perror("Too few arguments \n");
}
if (arg == NULL)
{
chdir(getenv("HOME"));
}
if (_strcmp(arg,"-"))
{
chdir(getenv("OLDPWD"));
}
if (path_exists(arg) == 1)
{
chdir(arg);
}
else
{
perror("Directory does not exist\n");
}
free(args);
}
/**
* exit_shell - exits the shell
* @arg: exit code
* Return: none
*/
void exit_shell(int arg)
{
if (arg == 0)
{
exit(EXIT_SUCCESS);
}
else if (arg == 1)
{
exit(EXIT_FAILURE);
}
else
{
exit(arg);
}
}