Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf just before a delay doesn't work in C

Tags:

c

printf

Does anyone know why if i put a printf just before a delay it waits until the delay is finished before it prints de message?

Code1 with sleep():

int main (void)
{
    printf ("hi world");
    system("sleep 3");    
}

Code2 with a self implemented delay:

void delay(float sec)
{
    time_t start;
    time_t current;
    time(&start);
    do{
        time(&current);
    }while(difftime(current,start) < sec);
}
int main (void)
{
    printf ("hi world");
    delay(3);    
}

And if:

printf ("hi world");
delay(3);    
printf ("hi world");
delay(3);    

it waits until the sum of sleeps and then it prints the messages at the same time

Why does this happen?

UPDATE: I writed delay("sleep 3") when i called delay, i meant delay(3). Corrected

like image 554
Xidobix Avatar asked Oct 06 '09 23:10

Xidobix


2 Answers

printf buffers it's output until a newline is output.

Add a fflush(stdout); to flush the buffers on demand.

like image 86
Roland Rabien Avatar answered Oct 04 '22 13:10

Roland Rabien


the standard output is not flush until you output a '\n' char.

try printf ("hi world\n");

like image 37
Ben Avatar answered Oct 04 '22 13:10

Ben