I did tried to use this and this but couldn't make it right (please notice the links before referring to it as a possible duplicate).
In my program I'm trying to run a program using a text file as it's input and redirecting the output of the program to a new file.
Here is my code :
if (fork() == 0) {
char *args[]={"program",">","output.txt",NULL};
int fd = open("/input.txt", O_RDONLY);
dup2(fd, 0);
execvp("program",args);
return 0;
}
program.c is my program I'm trying to run(not my main program)
/input.txt is the file I want to use as an input to my program.c
and output.txt is the file I want to redirect the output of program to
I know that for redirecting my program output I should use programname>outputfile.
But I can't make it work, I thing maybe I'm doing something wrong with the args array. What is the right way to sent input.txt as the input for program.c and redirect it's output to output.txt? (note that my main program is not program.c)
Any help would be appreciated
opena file and usedup2to replace stdout, exactly as the answer in the duplicate says and the answer below says too.