I want to redirect a content of input.txt file to stdin.
I tried:
int RunCompiledFile(char *path, char * input, char *thirdLine, char* name){
int fdFile = open(input, O_RDONLY), exitStatus, check,
fdFileOutput = open("newOutput.txt", O_RDWR|O_CREAT, 0777), status;
char* args[] = {"comp.out", "newOutput.txt", thirdLine};
char buffer[100];
pid_t pid;
dup2(0, fdFile);
dup2(fdFileOutput , 1);
getcwd(buffer, 95);
i = strlen(buffer);
buffer[i] = '/';
buffer[++i] = '\0';
check = execv(buffer,"a.out");
close(fdFileOutput);
//if ((pid = fork()) == 0){
check = execvp("comp.out", args);
// return 5;}
wait(&status);
exitStatus = WEXITSTATUS(status);
switch (exitStatus){
case 1:
result("0", name, BADOUTPUT);
unlink("newOutput.txt");
return 1;
case 2:
if (depth){
char buffer[5];
sprintf(buffer, "%d", 100 - (10 * depth));
result(buffer, name, WRONGDIRECTORY);}
else
result("100", name, GREATJOB);
unlink("newOutput.txt");
return 1;
case 3:
result("80", name, SIMILLAROUTPUT);
unlink("newOutput.txt");
return 1;
}
return fdFileOutput;
}
But becuase of all the forks it's hard to debbug. the execv - after the "getcwd" returns -1. a.out is a program the gets input via scanf(), and then does something and printf the answer.
I am supposed to get a file, turn it to stdin for the fgets of a.out, and then open a new file for the output of a.out.
it's still doesn't work, I tried your fixes:
dup2(fdFile, STDIN_FILENO);
dup2(fdFileOutput, STDOUT_FILENO);
getcwd(buffer, 95);
i = strlen(buffer);
buffer[i] = '/';
buffer[++i] = 'a';
buffer[++i] = '.';
buffer[++i] = 'o';
buffer[++i] = 'u';
buffer[++i] = 't';
buffer[++i] = '\0';
close(fdFileOutput);
close(fdFile);
check = execv(buffer,"a.out");
but the return from execv is still -1. the a.out is working on different users (my friends tried it before).