终端控制转义序列

@Daniate  October 24, 2021

本文首发于Daniate的个人网站,文章链接:https://daniate.com/archives/298/

参考:ANSI/VT100 Terminal Control Escape Sequences

宏定义

#ifndef VT100_H
#define VT100_H

/**
 * reference: https://www2.ccs.neu.edu/research/gpc/VonaUtils/vona/terminal/vtansi.htm
 */
#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 //VT100_H

在终端中展示任务处理进度

#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, // 0.1 秒
    };

    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;
}

知识共享许可协议
本作品由Daniate采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。


评论已关闭