Home > Net >  Does not flushing a buffer lead to files having incorrect output
Does not flushing a buffer lead to files having incorrect output

Time:10-24

In the code below, if I don't flush the buffer using fflush(STDOUT), could it be that FILE2 ends up getting both "Hello world 1" and "Hello world 2" since the buffer might be flushed at the end of the program and it might be holding both those statements by the end?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int FILE1 = dup(STDOUT_FILENO);
    int FILE2 = open("HelloWorld.txt",O_WRONLY|O_CREAT,0666);


    dup2(FILE1,STDOUT_FILENO);
    printf("Hello World 1\n");

    //THE LINE OF CONCERN
    fflush(stdout);

    dup2(FILE2,STDOUT_FILENO);

    printf("Hello World 2\n");
    close(FILE2);
    close(FILE1);
    return 0;
}

CodePudding user response:

The problem is that you work on different levels here. The stdio-system and stdout will have its own buffer which will not be closed or flushed when you do the second dup2 call. The contents of the stdout buffer will still remain and be written when stdout is closed at process termination.

So the fflush call is needed to actually flush the stdout buffer to the "file".

  • Related