Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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;
}

I've done that, long ago. There are two ways.

  1. Use a library like ncurses to give you control over the terminal. This works well if you want to do a lot of this kind of stuff. If you just one this in one little spot, it's obviously overkill.

  2. Print a control character.

First you print "/", then 0x08 (backspace), then "-", then 0x08, then "\"....

The backspace character moves the cursor position back one space, but leaves the current character there until you overwrite it. Get the timing right (so it doesn't spin to fast or slow) and you're golden.

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;
}

There is no truly "standard" way to do this, since the C Standard Library (http://members.aol.com/wantondeb/) does not provide functions to do raw terminal/console output.

In DOS/Windows console, the standard-ish way to do it is with conio.h, while under Unix/Linux the accepted library for this purpose is ncurses (ncurses basically encapsulates the control-character behavior that MBCook describes, in a terminal-independent way).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top