参考:ANSI/VT100 Terminal Control Escape Sequences
宏定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
   | #ifndef VT100_H #define VT100_H
 
 
 
  #define VT100_CURSOR_UP_ONE_ROW   "\033[A"
  #define VT100_ERASE_END_OF_LINE   "\033[K" #define VT100_ERASE_START_OF_LINE "\033[1K" #define VT100_ERASE_LINE          "\033[2K"
  #define VT100_FG_COLOR_BLACK      "\033[30m" #define VT100_FG_COLOR_RED        "\033[31m" #define VT100_FG_COLOR_GREEN      "\033[32m" #define VT100_FG_COLOR_YELLOW     "\033[33m" #define VT100_FG_COLOR_BLUE       "\033[34m" #define VT100_FG_COLOR_MAGENTA    "\033[35m" #define VT100_FG_COLOR_CYAN       "\033[36m" #define VT100_FG_COLOR_WHITE      "\033[37m"
  #define VT100_BG_COLOR_BLACK      "\033[40m" #define VT100_BG_COLOR_RED        "\033[41m" #define VT100_BG_COLOR_GREEN      "\033[42m" #define VT100_BG_COLOR_YELLOW     "\033[43m" #define VT100_BG_COLOR_BLUE       "\033[44m" #define VT100_BG_COLOR_MAGENTA    "\033[45m" #define VT100_BG_COLOR_CYAN       "\033[46m" #define VT100_BG_COLOR_WHITE      "\033[47m"
  #define VT100_RESET_ALL_ATTRS     "\033[0m"
  #endif 
 
  | 
 
在终端中展示任务处理进度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
   | #include <stdio.h> #include <stdlib.h> #include <time.h>
  #include "VT100.h"
  #define NB_TASKS (200)  #define NB_HYPHEN (50) 
  int main(int argc, const char *argv[]) {
      const struct timespec rqtp = {             .tv_sec = 0,             .tv_nsec = 100000000L,      };
      for (int i = 0; i <= NB_TASKS; ++i) {         printf("In progress: [");         int progress = i * 100 / NB_TASKS;         int n = progress * NB_HYPHEN / 100;         for (int j = 0; j < n; ++j) {             printf(VT100_FG_COLOR_GREEN "#" VT100_RESET_ALL_ATTRS);         }         for (int j = n; j < NB_HYPHEN; ++j) {             printf(" ");         }         printf("] " VT100_FG_COLOR_RED "%3d%%" VT100_RESET_ALL_ATTRS "\r\n", progress);
          if (NB_TASKS == i) {             printf("Task completed!\r\n");             break;         }
          nanosleep(&rqtp, NULL);
          printf(VT100_CURSOR_UP_ONE_ROW VT100_ERASE_LINE);
          fflush(stdout);     }
      return EXIT_SUCCESS; }
 
  |