-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.c
More file actions
82 lines (64 loc) · 1.38 KB
/
utils.c
File metadata and controls
82 lines (64 loc) · 1.38 KB
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
#include "headers.h"
#include "commands.h"
#include "colours.h"
#include "utils.h"
#include "Features/redirection.h"
#include "Features/pipe.h"
void tokenizeCommand(char *token)
{
char *argv[1000], *p;
int flag = 0;
int stdoutSaved = dup(STDOUT_FILENO), stdinSaved = dup(STDIN_FILENO);
if (checkPipe(token))
{
piping(token, stdoutSaved, stdinSaved);
return;
}
if (checkRedirection(token))
flag = 1;
p = strtok_r(token, " \t\r", &token);
argv[0] = p;
int len = 1;
while ((p = strtok_r(NULL, " \t\r", &token)) != NULL)
{
argv[len] = p;
len++;
}
if (flag)
len = redirectIO(len, argv);
if (len)
commands(len, argv);
else
return;
fileStream(stdoutSaved, STDOUT_FILENO);
fileStream(stdinSaved, STDIN_FILENO);
}
int strToInt(char *str)
{
int num = 0;
int n = strlen(str);
for (int i = 0; i < n; i++)
{
int converted = str[i] - '0';
if (converted < 0 || converted > 9)
return 0;
num = (num * 10) + converted;
}
if (num < 0)
return 0;
return num;
}
int fileStream(int fd, int stream)
{
if (fd < 0)
{
printf("Error: File not found\n");
return 0;
}
if (dup2(fd, stream) < 0)
{
printf("Error: Cannot redirect\n");
return 0;
}
close(fd);
}