-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredirect_get.c
More file actions
executable file
·87 lines (78 loc) · 1.67 KB
/
Copy pathredirect_get.c
File metadata and controls
executable file
·87 lines (78 loc) · 1.67 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
83
84
85
86
87
#include "minishell.h"
#include <fcntl.h>
#include <stdio.h>
#include <readline/readline.h>
#include <unistd.h>
int free_return_int(void *to_free, int to_return)
{
free(to_free);
return (to_return);
}
static int get_heredocument(char *delimiter)
{
int fd;
char *str;
char *path;
path = get_temp_path();
if (!path)
return (0);
fd = open(path, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0644);
if (fd == -1)
return (free_return_int(path, -1));
str = readline("> ");
while (str && ft_strncmp(str, delimiter, ft_strlen(delimiter) + 1))
{
write(fd, str, ft_strlen(str));
write(fd, "\n", 1);
free(str);
str = readline("> ");
}
if (!str)
ft_putstr_fd("warning: here-document delimited by end-of-file\n", 1);
free(str);
close(fd);
fd = open(path, O_RDONLY);
unlink(path);
return (free_return_int(path, fd));
}
static int redir_output(int redir, char *path)
{
int fd;
if (redir == 1)
fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0644);
else
fd = open(path, O_CREAT | O_WRONLY | O_APPEND, 0644);
return (fd);
}
static int redir_input(int redir, char *path)
{
int fd;
if (redir == 3)
fd = open(path, O_RDONLY);
else
fd = get_heredocument(path);
return (fd);
}
int redirect_get(t_pipe *no_p, int redir, char *path)
{
int fd;
if (redir == 1 || redir == 2)
{
if (no_p->fd_out != 1)
close(no_p->fd_out);
fd = redir_output(redir, path);
if (fd < 0)
return (print_free_return(path, fd));
no_p->fd_out = fd;
}
else if (redir == 3 || redir == 4)
{
if (no_p->fd_in != 0)
close(no_p->fd_in);
fd = redir_input(redir, path);
if (fd < 0)
return (print_free_return(path, fd));
no_p->fd_in = fd;
}
return (free_return_int(path, 1));
}