Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string?
When I run something like
for (i = 1; i <= 10; i++) {
sleep(1);
printf(".");
}
then what I would expect is one dot per second ten times. What I get is ten dots once after ten seconds. Why is that so, and how do I get the program to actually print one point (or do other things) each second (or different time interval)?
The sleep() method in the C programming language allows you to wait for just a current thread for a set amount of time. The sleep() function will sleep the present executable for the time specified by the thread.
sleep() function is provided by unistd. h library which is a short cut of Unix standard library.
The sleep() function shall cause the calling thread to be suspended from execution until either the number of realtime seconds specified by the argument seconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process.
The printf()
is buffering the data, you can force it to flush that data with fflush(stdout)
:
for (i = 1; i<=10; i++)
{
sleep(1);
printf(".");
fflush(stdout);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With