83 lines
2.2 KiB
C
83 lines
2.2 KiB
C
#include "include/redirection.h"
|
|
#include <string.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
void detectRedirections(char **args, Redirection *in, Redirection *out) {
|
|
in->type = REDIRECT_NONE;
|
|
in->filename = NULL;
|
|
out->type = REDIRECT_NONE;
|
|
out->filename = NULL;
|
|
|
|
int j = 0;
|
|
for (int i = 0; args[i] != NULL; i++) {
|
|
if (strcmp(args[i], "<") == 0) {
|
|
if (args[i + 1] != NULL) {
|
|
in->type = REDIRECT_IN;
|
|
in->filename = args[i+1];
|
|
i++; // skip filename
|
|
}
|
|
} else if (strcmp(args[i], ">") == 0) {
|
|
if (args[i + 1] != NULL) {
|
|
out->type = REDIRECT_OUT;
|
|
out->filename = args[i+1];
|
|
i++;
|
|
}
|
|
} else if (strcmp(args[i], ">>") == 0) {
|
|
if (args[i + 1] != NULL) {
|
|
out->type = REDIRECT_APPEND;
|
|
out->filename = args[i+1];
|
|
i++;
|
|
}
|
|
} else {
|
|
args[j++] = args[i];
|
|
}
|
|
}
|
|
args[j] = NULL;
|
|
}
|
|
|
|
int applyRedirections(Redirection in, Redirection out) {
|
|
if (in.type == REDIRECT_IN) {
|
|
int fd = open(in.filename, O_RDONLY);
|
|
if (fd < 0) {
|
|
perror("open input");
|
|
return -1;
|
|
}
|
|
if (dup2(fd, STDIN_FILENO) < 0) {
|
|
perror("dup2 input");
|
|
close(fd);
|
|
return -1;
|
|
}
|
|
close(fd);
|
|
}
|
|
|
|
if (out.type == REDIRECT_OUT) {
|
|
int fd = open(out.filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
|
|
if (fd < 0) {
|
|
perror("open output");
|
|
return -1;
|
|
}
|
|
if (dup2(fd, STDOUT_FILENO) < 0) {
|
|
perror("dup2 output");
|
|
close(fd);
|
|
return -1;
|
|
}
|
|
close(fd);
|
|
} else if (out.type == REDIRECT_APPEND) {
|
|
int fd = open(out.filename, O_WRONLY | O_CREAT | O_APPEND, 0644);
|
|
if (fd < 0) {
|
|
perror("open output append");
|
|
return -1;
|
|
}
|
|
if (dup2(fd, STDOUT_FILENO) < 0) {
|
|
perror("dup2 output append");
|
|
close(fd);
|
|
return -1;
|
|
}
|
|
close(fd);
|
|
}
|
|
return 0;
|
|
}
|