Print spinning cursor in a terminal running application using C

后端 未结 5 985
Happy的楠姐
Happy的楠姐 2021-02-01 07:15

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 pos

相关标签:
5条回答
  • 2021-02-01 08:01

    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;
    }
    
    0 讨论(0)
  • 2021-02-01 08:12

    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.

    0 讨论(0)
  • 2021-02-01 08:13

    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.

    0 讨论(0)
  • 2021-02-01 08:15

    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).

    0 讨论(0)
  • 2021-02-01 08:21

    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;
    }
    
    0 讨论(0)
提交回复
热议问题