-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_redirection.c
More file actions
102 lines (92 loc) · 2.28 KB
/
Copy pathparse_redirection.c
File metadata and controls
102 lines (92 loc) · 2.28 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
** EPITECH PROJECT, 2025
** B-PSU-200-LYN-2-1-minishell2-pierre.baud
** File description:
** parse_redirection
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include "my.h"
void handle_redirection(char **args, int *i, redirection_t *redir)
{
if (my_strcmp(args[*i], "<") == 0) {
redir->input_file = args[*i + 1];
(*i)++;
}
if (my_strcmp(args[*i], ">") == 0) {
redir->output_file = args[*i + 1];
redir->append = 0;
(*i)++;
}
if (my_strcmp(args[*i], ">>") == 0) {
redir->output_file = args[*i + 1];
redir->append = 1;
(*i)++;
}
}
redirection_t parse_redirections(char **args)
{
redirection_t redir = {NULL, NULL, 0};
int i = 0;
int j = 0;
for (i = 0; args[i] != NULL; i++) {
if (my_strcmp(args[i], "<") == 0 || my_strcmp(args[i], ">") == 0 ||
my_strcmp(args[i], ">>") == 0) {
handle_redirection(args, &i, &redir);
continue;
}
args[j] = args[i];
j++;
}
args[j] = NULL;
return redir;
}
void handle_input_redirection(redirection_t redir)
{
int fd = 0;
if (!redir.input_file)
return;
fd = open(redir.input_file, O_RDONLY);
if (fd == -1) {
perror("Erreur ouverture fichier entrée");
exit(1);
}
dup2(fd, STDIN_FILENO);
close(fd);
}
void handle_output_redirection(redirection_t redir)
{
int fd = 0;
int flags = 0;
if (!redir.output_file)
return;
flags = O_WRONLY | O_CREAT | (redir.append ? O_APPEND : O_TRUNC);
fd = open(redir.output_file, flags, 0644);
if (fd == -1) {
perror("Erreur ouverture fichier sortie");
exit(1);
}
dup2(fd, STDOUT_FILENO);
close(fd);
}
void find_and_execute_command(char **args, char **envc)
{
char *path = create_path(envc);
char *dir = strtok(path, ":");
char full_path[1024];
while (dir) {
if (!is_valid_path_length(dir, args[0])) {
create_full_path(full_path, dir, args[0]);
execve_f(full_path, args, envc);
}
dir = strtok(NULL, ":");
}
write(2, args[0], my_strlen(args[0]));
write(2, ": Command not found\n", 20);
exit(84);
}