I am writing a program which creates a txt files input.txt
and it uses it as input of exec()
. I have problems redirecting its output to another file output.txt
and they seems to be linked to input.txt
writing.
If I use fwrite(array, 4, 1, file)
the redirection works.
If I use fwrite(array, sizeof(array), 1, file)
or fprint
, it doesn't.
FILE *finput = fopen("input.txt", "w");
for (int i=0; i<dimension; i++)
{
char c; // I get it from another file, it isnt't important.
char arr[1];
arr[0] = c;
// WORKING LINE OF CODE
fwrite(arr, 4, 1, finput);
// NOT-WORKING LINE OF CODE
// fwrite(arr, sizeof(arr), 1, finput);
// ANOTHER NOT-WORKING LINE OF CODE
// fprintf(finput, "%c", c);
}
pid_t pid;
int status = -1;
pid = fork();
if (pid == -1)
{
printf("ERROR.");
}
else if ( pid == 0)
{
int fdOutput = creat("output.txt", 0777);
dup2(fdOutput, 1);
dup2(fdOutput, 2);
close(fdOutput);
// awkScript is an awk program string
int executionResult = execl("/usr/bin/gawk", "gawk", awkScript, "input.txt", (char*)NULL);
// ...
}
If I write the working line of code, at the end of the program I have some text in the output.txt
file. Otherwise, it is completely empty.
The weirdest thing is that input.txt
works anyway, it is always correctly written. So I can't understand why it should be connected to its writing. If I execute the command:
gawk $awkScript input.txt
The output is printed in all the three ways used to write input.txt