代码之家  ›  专栏  ›  技术社区  ›  Misha M

在运行C的终端应用程序中打印旋转光标

  •  15
  • Misha M  · 技术社区  · 17 年前

    如何在使用标准C的终端中运行的实用程序中打印旋转诅咒?

    我在找在屏幕上相同位置反复打印的东西。

    谢谢

    5 回复  |  直到 16 年前
        1
  •  21
  •   Greg Hewgill    17 年前

    你可以用退格符( \b 像这样:

    printf("processing... |");
    fflush(stdout);
    // do something
    printf("\b/");
    fflush(stdout);
    // do some more
    printf("\b-");
    fflush(stdout);
    

    等等,你需要 fflush(stdout) 因为通常在输出换行符之前都会缓冲stdout。

        2
  •  12
  •   Diego Zamboni    17 年前

    下面是一些示例代码。任务完成时,每隔一段时间调用一次advance_cursor()。

    #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;
    }
    
        3
  •  2
  •   MBCook    17 年前

    我早就这么做了。有两种方法。

    1. 使用像ncurses这样的库可以控制终端。如果你想做很多这样的事情,这很有效。如果你只在一个小地方放一个,那显然是杀伤力太大了。

    2. 打印控制字符。

    首先打印“/”,然后是0x08(退格),然后是“-”,然后是0x08,然后是“\”…

    退格符将光标位置向后移动一个空格,但保留当前字符,直到覆盖它。把握好时机(这样它就不会转得快或慢),你就是黄金。

        4
  •  2
  •   Miki Tebeka    17 年前

    您也可以使用 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;
    }
    
        5
  •  1
  •   Dan Lenski    17 年前

    没有真正的“标准”方法可以做到这一点,因为C标准库( http://members.aol.com/wantondeb/ )不提供执行原始终端/控制台输出的功能。

    在DOS/Windows控制台中,标准的ISH方法是 conio.h ,而在UNIX/Linux下,为此目的接受的库是 ncurses ( 纳克西斯 基本上以终端独立的方式封装mbcook描述的控制字符行为)。