3

I can't understand why following code works like this..I mean: instead of printing "hello" after each one second delay...it wait 5 second and display hellohellohellohellohello at once.

#include <stdio.h>

int i;
for(i=0; i<5; i++) {
   printf("hello");
   sleep(1);
}       
jww
  • 83,594
  • 69
  • 338
  • 732
ak44
  • 59
  • 1
  • 4
  • You need to flush standard output somehow. http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin –  Sep 02 '14 at 15:56
  • 1
    You did not include your code in a `main` function... Did you really compile and execute that? – Jay Sep 02 '14 at 16:01

5 Answers5

12

The output of printf() (stdout) is line buffered by default if the output is going to a tty. You need one of

printf("hello\n");

or

printf("hello");
fflush(stdout);

The latter will explicitly flush the output each iteration.

FatalError
  • 47,677
  • 13
  • 93
  • 113
4

printf do not print immediatly, instead it cache it line per line.

Add "\n" (newline) add the end of your string printf("hello\n"); or use write function instead write(STDOUT_FILENO, "hello", sizeof("hello"));.

mantal
  • 879
  • 1
  • 19
  • 34
3

You are writing to standard output (stdout), which is buffered. If you want the content to be immediately printed, you may flush the output or insert a newline.

You can add a \n to the end of your string so as to print the newline -- change your printf line to:

   printf("hello\n");

For flushing the stdout buffer call fflush on it, after the printf:

#include <stdio.h>

int main() {
    int i;
    for(i=0; i<5; i++) {
       printf("hello");
       fflush(stdout);
       sleep(1);
    }       
}
Jay
  • 9,293
  • 6
  • 44
  • 67
1

In general the output can be buffered. That means the implementation collects several bytes before actually writing to the console. You can explicitly write the buffer by fflush(stdout). This is true for all file descriptors, one of which is stdout, the terminal output. You can disable the buffering with setbuff(stdout, NULL), but this is almost never a good idea performance wise.

fweik
  • 371
  • 2
  • 5
0

Try this:

int i;
for(i=0;i<5;i++){
printf("hello\n");
i=0;
sleep(1);
}