Print spinning cursor in a terminal running application using C

后端 未结 5 1082
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 
    #include 
    
    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;
    }
    

提交回复
热议问题