怎样在 Linux/OS X 下输出带颜色的字符串

命令行下全是一个颜色未免有点单调, 通过 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

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