Monday, August 27, 2007

stdout is buffered, stderr is not buffered

stdout is buffered. Data written to stdout is not sent to the console (or other device, if it’s redirected) until the buffer fills, the program exits normally, or stdout is closed

#include <>
int main(int argc, char **argv)
{
while(1)
{
printf("the ");
sleep (1);
}
return 0;
}


this loop does not print "the" every second; instead, "the" are buffered, and a bunch of them are printed together when the buffer fills.

You can explicitly flush the buffer by calling the following:
fflush (stdout);


In contrast, stderr is not buffered; data written to stderr goes directly to the console. "the" do appear once a second:

#include <>
int main(int argc, char **argv)
{
while(1)
{
fprintf(stderr, "the ");
sleep (1);
}
return 0;
}

No comments:

Post a Comment