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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With