I am writing a redirection function that writes the output of a command to a given file name.
For instance:
echo Hello World > hello.txt will write "Hello World" in hello.txt.
ls -al > file_list.txt will write a list of all file / directory names in the current directory to list.txt file.
My function is still defined as:
int my_redirect(char **args, int count) {
if (count == 0 || args[count + 1] == NULL) {
printf("The redirect function must follow a command and be followed by a target filename.\n");
return 1;
}
char *filename = args[count + 1];
char *command = (char *) malloc(256);
for (int i = 0; i < (count); i++) {
if (i == 0) {
strcpy(command, args[i]);
strcat(command, " ");
}
else if (i == count - 1) {
strcat(command, args[i]);
}
else {
strcat(command, args[i]);
strcat(command, " ");
}
}
free(command);
return 1;
}
where args[count]- ">".
How to execute a command given by a line from args[0]to args[count - 1]to a file specified in args[count + 1]?
EDIT
These are the instructions that were given to us:
"Improve your shell by adding a redirection for stdout to the file. Try only after completing the function 1. Parse the line for>, take everything before the command and the first word after the file name (ignore <, →, |, etc.).
1 (stdin 0, stderr 2). , 1 dup2.
int f = open( filename , O_WRONLY|O_CREAT|O_TRUNC, 0666) ;
dup2( f , 1 ) ;
: open, . "