2

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

Luca
  • 51
  • 3
  • 1
    I'm confused. (1) You are passing a FILE* to execl ? (2) You write a record of 4 bytes but your array is 1 byte? – Gem Taylor May 23 '19 at 10:16
  • 1) No, I just made a mistake in formatting my code here. I edited the question 2) Well, I tried with sizeof(arr) but it didn't work. So I tried with 4 bytes and it did. – Luca May 23 '19 at 10:21

1 Answers1

3

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • As I said in the upper comment, the size of 4 was just a way to make it work. That isn't the problem, because the file was correctly written. But I found out that the fclose was at the end of the fork, so you are completely right about it. Moving it before the fork, it seems to work. Thank you – Luca May 23 '19 at 10:29
  • So most likely, writing 4 bytes per loop just caused it to write a block of cached data to the file, while writing 1 byte didn't. – Gem Taylor May 23 '19 at 11:44