I want to make an animated processing icon outputted in console via C.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
void render_processing_icon(int turnovers_qt) {
char *icon_characters = "|/-\\\0";
for (int i = 0; i < turnovers_qt * 8; i++) {
printf("\b%c", icon_characters[i % 4]);
usleep(500000); // sleep for a half of a second
}
printf("\n");
}
int main(int argc, char *argv[]) {
render_processing_icon(2);
printf("CONTROL MESSAGE\n");
return 0;
}
But after usleep()
time (0.5s * turnovers * 8) is over, program outputs this (without any animation, as you've guess):
$ \
$ CONTROL MESSAGE
sleep()
works the same, BASH sleep
via sytstem()
too. I just have no idea what's the problem.
It is because you are not flushing the printf
to the terminal. To save time the terminal usually buffers output. At some point when the buffer is full or in some terminals when you write \n
to the stream it will flush automatically.
Try using fflush(stdout)
before the usleep
in your for
loop to force this flush.