tags:

views:

296

answers:

3

I have written a printf() statement like below:

printf("hello\n");

this works fine when built using Linux' gcc compiler. However if I write

printf("hello");

the print doesn't appear on the screen. There is some buffering mechanism it seems? Can anybody give me more information on this?

+13  A: 

Try the fflush() call. Typically writing to a screen or file is very expensive, so the data is buffered until it needs to be written. A \n usually is enough to do the trick (buffers generally store only 1 line at a time anyway), but if you need to flush the buffer - use that flush call.

gbjbaanb
In particular, fflush(STDOUT) will flush the standard output stream that printf uses.
Nate Kohl
And remember, kiddies, stdout is buffered by default, stderr isn't.
paxdiablo
BTW, fflush(NULL) will flush *all* open buffers.
gbjbaanb
stdout is line buffered when pointing to a terminal by default. (otherwise block buffered, I think)
Hasturkun
+6  A: 

Even if buffering isn't a problem, if you don't print the newline your shell's prompt might be clobbering the output.

I'm not sure in which environment you are running this, but if you are for example using gcc in a unix shell and at the end of your program do printf("hello") it won't print a newline before your shells prompt is displayed. The prompt will be printed on that same line, sometimes overwriting the entire line depending on kind of prompt you have set up.

Andre Miller
Only if it's one of those deviant ones with a carriage return in it :-)
paxdiablo
Yes, and even without a carriage return the prompt will be displayed appended to the last line of output, making it appear as if nothing was printed to an unobservant person. Of course, I'm not admitting to being that unobservant in the past *cough cough*
Andre Miller
+2  A: 

I posted here about unbuffered IO on windows..

but its a standard c-call to setvbuf

setvbuf(stdout, (char *)NULL, _IONBF, 0); //unbuffered stdout
ShoeLace