程序的颜色输出在BASH下运行

Pat*_*jel 10 c++ linux bash colors

我需要能够使终端上的一些文本更加引人注目,我想的是使文本变为彩色.无论是实际文本,还是每个字母的矩形空间(想想vi的光标).我认为对我的应用程序来说重要的两个额外规格是:程序应该是独立于发行版的(确定代码只能在BASH下运行),并且在写入文件时不应输出额外的字符(来自实际代码,或管道输出时)

我在网上搜索了一些信息,但我只能找到弃用的cstdlib(stdlib.h)的信息,我需要(实际上,它更像是"想要")使用iostream的功能来完成它.

orl*_*rlp 13

大多数终端都遵循ASCII颜色序列.ESC然后[,它们通过输出,然后输出以分号分隔的颜色值列表来工作m.这些是常见的值:

Special
0  Reset all attributes
1  Bright
2  Dim
4  Underscore   
5  Blink
7  Reverse
8  Hidden

Foreground colors
30  Black
31  Red
32  Green
33  Yellow
34  Blue
35  Magenta
36  Cyan
37  White

Background colors
40  Black
41  Red
42  Green
43  Yellow
44  Blue
45  Magenta
46  Cyan
47  White
Run Code Online (Sandbox Code Playgroud)

因此输出"\033[31;47m"应使终端前(文本)颜色为红色,背景颜色为白色.

你可以很好地用C++形式包装它:

enum Color {
    NONE = 0,
    BLACK, RED, GREEN,
    YELLOW, BLUE, MAGENTA,
    CYAN, WHITE
}

std::string set_color(Color foreground = 0, Color background = 0) {
    char num_s[3];
    std::string s = "\033[";

    if (!foreground && ! background) s += "0"; // reset colors if no params

    if (foreground) {
        itoa(29 + foreground, num_s, 10);
        s += num_s;

        if (background) s += ";";
    }

    if (background) {
        itoa(39 + background, num_s, 10);
        s += num_s;
    }

    return s + "m";
}
Run Code Online (Sandbox Code Playgroud)