#include <stdio.h>
int main(){
char a[2] = {0};
a[0] = 't';
printf("%s", a);
scanf("%c", a);
return 0;
}
scanf
here will cause an automatic flush of stdout.
Running a.out
will print t
on the terminal before running scanf, more info: How is printf getting flushed before scanf is executed?
However, doing a.out > out.txt
and terminating it with ^C
does not print anything inside out.txt
yet the output still appeared on the screen without redirecting stdout with >
.
If stdout is being flushed then why out.txt
is still empty?
If it's not being flushed then how did t
appear on the screen in the first example?
(I know using \n
or a manual fflush or properly terminating the program will fix the issue, i'm just curious about this behaviour).
CodePudding user response:
The key is the word interactive:
The input and output dynamics of interactive devices shall take place as specified in 7.21.3.
As soon as you redirect the standard output to a file, it is no longer interactive.
For example the Linux C standard library actually executes the analogue of the isatty
library call to figure this out. If it figures out that standard output is not directed to file it will also break this relationship. It will also increase the I/O performance of programs that work as part of a command pipeline.
You can yourself test whether stdout
is connected to a terminal by executing
#include <unistd.h>
printf("stdout is connected to a terminal: %d\n", isatty(fileno(stdout)));