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
There are multiple issues with this code (such as the size 4 … where does this come from? Your array is 1 byte long; so this is undefined behaviour) but the fundamental reason why it fails is that you fail to close your file. This means the output buffer never gets flushed, and no output written.
Either fclose
the file, or at least fflush
it after the write.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.