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

Mis*_*a M 15 c printf

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

我正在寻找打印的东西:\ |/ - 在屏幕上的相同位置一遍又一遍?

谢谢

Gre*_*ill 21

您可以\b像这样使用退格符():

printf("processing... |");
fflush(stdout);
// do something
printf("\b/");
fflush(stdout);
// do some more
printf("\b-");
fflush(stdout);
Run Code Online (Sandbox Code Playgroud)

您需要,fflush(stdout)因为通常stdout会被缓冲,直到您输出换行符.


zza*_*oni 12

这是一些示例代码.任务完成时,每隔一段时间调用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;
}
Run Code Online (Sandbox Code Playgroud)