Why printf () is not output to the file when stdout is redirected to this file?

The following simple C program:

 #include <unistd.h> #include <stdio.h> int main(void) { while (1) { printf("Hello World\n"); sleep(1); } } 

Create and run it, the terminal will print " Hello World ":

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

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

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

Why is printf output to a file that stdout redirected to?

+5
source share
1 answer

For the terminal, only the default is a string buffer. Here you redirected stdout to a file. So now stdout does not indicate a terminal. It indicates a file. For a file, it is by default fully buffered. So, you reset stdout after writing it.

Send an answer for this question .

Like @ js1 said, you should call fflush (stdout) after writing it.

0
source

Source: https://habr.com/ru/post/1263292/


All Articles