#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int i=0;
while(i<10)
{
printf("%d", i);
usleep(10000); // or sleep(1)
i++;
}
return 0;
}
I want the program to last 10 secs, i.e. print 1 – wait 1 sec – print 2 – wait 1 sec and so on until the end. But it doesn’t do that – it just waits for all the time (10 secs) and then prints the whole array of numbers together without any time delays between them, it just prints 0123456789 at once.
EDIT: I tried with sleep() instead of usleep but it’s the same
How to fix it ? And why it’s like that ?
Your output buffer is not being flushed. By default, output is written when a new line appears in the stream. Change your
printfto this:or try this:
Also, if you want to remove the line-buffering behaviour, you can use
setvbuf()and the_IONBUFmode.