How would I print a spinning curser in a utility that runs in a terminal using standard C?
I'm looking for something that prints: \ | / - over and over in the same position on the screen?
Thanks
You could use the backspace character (\b
) like this:
printf("processing... |");
fflush(stdout);
// do something
printf("\b/");
fflush(stdout);
// do some more
printf("\b-");
fflush(stdout);
etc. You need the fflush(stdout)
because normally stdout is buffered until you output a newline.
Here's some example code. Call advance_cursor() every once in a while while the task completes.
#include <stdio.h>
void advance_cursor() {
static int pos=0;
char cursor[4]={'/','-','\\','|'};
printf("%c\b", cursor[pos]);
fflush(stdout);
pos = (pos+1) % 4;
}
int main(int argc, char **argv) {
int i;
for (i=0; i<100; i++) {
advance_cursor();
usleep(100000);
}
printf("\n");
return 0;
}
You can also use \r:
#include <stdio.h>
#include <unistd.h>
void
advance_spinner() {
static char bars[] = { '/', '-', '\\', '|' };
static int nbars = sizeof(bars) / sizeof(char);
static int pos = 0;
printf("%c\r", bars[pos]);
fflush(stdout);
pos = (pos + 1) % nbars;
}
int
main() {
while (1) {
advance_spinner();
usleep(300);
}
return 0;
}
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