命令行下全是一个颜色未免有点单调, 通过 ANSI escape code 可以输出一些带颜色的字符串.

StackOverflow 有介绍, 我们可以输出如下一些字符串, 使得这些字符串之后的内容改变颜色.

Black        0;30     Dark Gray     1;30
Red          0;31     Light Red     1;31
Green        0;32     Light Green   1;32
Brown/Orange 0;33     Yellow        1;33
Blue         0;34     Light Blue    1;34
Purple       0;35     Light Purple  1;35
Cyan         0;36     Light Cyan    1;36
Light Gray   0;37     White         1;37

C 语言代码如下:

#include <stdio.h>

#define T_COLOR_NONE "\033[0m"

#define T_COLOR_BLACK "\033[0;30m"
#define T_COLOR_RED "\033[0;31m"
#define T_COLOR_GREEN "\033[0;32m"
#define T_COLOR_ORANGE "\033[0;33m" // BROWN
#define T_COLOR_BLUE "\033[0;34m"
#define T_COLOR_PURPLE "\033[0;35m"
#define T_COLOR_CYAN "\033[0;36m"
#define T_COLOR_LIGHT_GRAY "\033[0;37m"

#define T_COLOR_DARK_GRAY "\033[1;30m"
#define T_COLOR_LIGHT_RED "\033[1;31m"
#define T_COLOR_LIGHT_GREEN "\033[1;32m"
#define T_COLOR_YELLOW "\033[1;33m"
#define T_COLOR_LIGHT_BLUE "\033[1;34m"
#define T_COLOR_LIGHT_PURPLE "\033[1;35m"
#define T_COLOR_LIGHT_CYAN "\033[1;36m"
#define T_COLOR_WHITE "\033[1;37m"

int main(int argc, char* argv[]) {
    printf("%sHello, World!%s\n", T_COLOR_RED, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_GREEN, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_ORANGE, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_BLUE, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_PURPLE, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_CYAN, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_LIGHT_GRAY, T_COLOR_NONE);

    printf("%sHello, World!%s\n", T_COLOR_DARK_GRAY, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_LIGHT_RED, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_LIGHT_GREEN, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_YELLOW, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_LIGHT_BLUE, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_LIGHT_PURPLE, T_COLOR_NONE);
    printf("%sHello, World!%s\n", T_COLOR_LIGHT_CYAN, T_COLOR_NONE);

    printf("%sHello, World!%s\n", T_COLOR_WHITE, T_COLOR_NONE);

    return 0;
}

效果如下: colored-string

Categories: Code

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

3 Comments

zz · August 26, 2016 at 10:35

QQbrowser 9.4.8699.400 QQbrowser 9.4.8699.400 Windows 10 x64 Edition Windows 10 x64 Edition

不错。
或直接在console:

$ printf "\033[0;33mOrange; \033[0mNormal color\n"

    yu · August 27, 2016 at 10:31

    Google Chrome 52.0.2743.116 Google Chrome 52.0.2743.116 Mac OS X  10.11.6 Mac OS X 10.11.6

    @zz 对。而且因为是终端的一个输出约定,putty 之类上都能看到

mooc · January 22, 2016 at 14:35

Firefox 43.0 Firefox 43.0 Windows 10 x64 Edition Windows 10 x64 Edition

这个功能不错,Mark一下

Leave a Reply

Your email address will not be published. Required fields are marked *