-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredirection.c
More file actions
73 lines (71 loc) · 1.76 KB
/
redirection.c
File metadata and controls
73 lines (71 loc) · 1.76 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
#include "headers.h"
#include "redirection.h"
int redir(char *inputs[], int args)
{
int fd;
for (int i = 0; i < args; i++)
{
if (strcmp(inputs[i], ">") == 0)
{
i++;
int fd = open(inputs[i], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0)
{
perror("ERROR");
return 1;
}
if (dup2(fd, STDOUT_FILENO) < 0)
{
perror("Could not duplicate file descriptor");
return 1;
}
close(fd);
}
else if (strcmp(inputs[i], "<") == 0)
{
i++;
int fd = open(inputs[i], O_RDONLY);
if (fd < 0)
{
perror("ERROR");
return 1;
}
if (dup2(fd, STDIN_FILENO) < 0)
{
perror("Could not duplicate file descriptor");
return 1;
}
close(fd);
}
else if (strcmp(inputs[i], ">>") == 0)
{
i++;
int fd = open(inputs[i], O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd < 0)
{
perror("ERROR");
return 1;
}
if (dup2(fd, STDOUT_FILENO) < 0)
{
perror("Could not duplicate file descriptor");
return 1;
}
close(fd);
}
}
}
int redirection(char *inputs[], int args)
{
for (int i = 0; i < args; i++)
{
if (strcmp(inputs[i], ">") == 0 || strcmp(inputs[i], ">>") == 0 || strcmp(inputs[i], "<") == 0)
{
if (redir(inputs, args) == 1)
{
return 1;
}
}
}
return 0;
}