1

Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string?

I was trying to answer some question on the forums, I encountered pretty interesting thing. Here is the code :

int main()
{
 int print_val = -1;

 while(1)
 {
  printf("%d \n", ++print_val);
  sleep(1);
 }
}

This works perfect. Now the fun enters.. Just change line no 7 to printf("%d ", ++print_val);(just remove linefeed!)

and now there is no output..!

So can any one please help me understand the behavior of sleep() function..? I think there is need to look at sleep() and not printf() because I have tried replacing it with fprintf() and putc(), giving just the same output.

I have tried this code on 32 bit Ubuntu as well as 32 bit Ubuntu in Virtual Machine.

Thanks Adorn

Community
  • 1
  • 1
Adorn
  • 1,403
  • 1
  • 23
  • 46
  • 3
    Try putting a fflush(stdout); right after the printf. – imreal Oct 31 '12 at 06:32
  • This has been answered many times. \n flushes the buffer. Printf by default is buffered output and you cannot predict when it actually prints – fkl Oct 31 '12 at 06:37
  • Thanks Nick, Rob Mayoff !! Did not think of 'fflush'ing. @robmayoff your link to previous question was pretty informative. Thanks. – Adorn Oct 31 '12 at 06:39
  • @fayyazkl yes! so sorry to ask this question! but i think its human nature to forget about some aspects and continue thinking in one direction only. My que indicates tht I was digging in direction of sleep(). – Adorn Oct 31 '12 at 06:43

1 Answers1

6

I feel the problem is with flushing the output buffer. If you don't put '\n' at the end of your string, then output buffer won't be flushed and printf won't print anything. It will only start printing when the output buffer is full. Please look at this question and this one.

Community
  • 1
  • 1
CCoder
  • 2,305
  • 19
  • 41