Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print spinning cursor in a terminal running application using C

Tags:

c

printf

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

like image 237
Misha M Avatar asked Oct 13 '08 22:10

Misha M


3 Answers

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.

like image 194
Greg Hewgill Avatar answered Oct 23 '22 05:10

Greg Hewgill


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;
}
like image 38
Diego Zamboni Avatar answered Oct 23 '22 07:10

Diego Zamboni


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;
}
like image 3
lazy1 Avatar answered Oct 23 '22 06:10

lazy1