Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why printf() does not output to a file, when stdout is redirected to that file?

Tags:

c

The following is a simple C program:

#include <unistd.h>
#include <stdio.h>

int main(void)
{
        while (1)
        {
                printf("Hello World\n");
                sleep(1);
        }
}

Build and run it, the "Hello World" will be printed in the terminal:

$ ./a.out
Hello World
Hello World
Hello World

But if the stdout is redirected to a file, after running a while, there is still nothing in the file:

$ ./a.out > log.txt
^C
$ cat log.txt
$

Why doesn't the printf output to the file which stdout is redirected to?

like image 798
Nan Xiao Avatar asked Jan 25 '17 00:01

Nan Xiao


People also ask

Does printf output to stdout?

printf by default writes on stdout , if you want to write to a specific stream you should use fprintf which accepts a FILE* as the destination stream. Also it's "std" out because it's called "standard" output.


1 Answers

For terminal only by default it is line buffer. In here you redirected the stdout to the file. So, now the stdout is not pointing a terminal. It pointing a file. For the file it is by default fully buffered. So, you have flush the stdout after writing it.

Refer the answer for this question.

As @js1, said, you have to call fflush(stdout) after writing it.

like image 127
sureshkumar Avatar answered Oct 17 '22 07:10

sureshkumar