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
printfto 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\nto the stream it will flush automatically.Try using
fflush(stdout)before theusleepin yourforloop to force this flush.