Howto Print A Colorful String on Linux Terminal With C Program

Author Avatar
Mutse Young 5月 15, 2011

As we know, we can display a colorful string on linux terminal with bash shell,
but what about c program?

In this post, I’ll talk about howto print a colorful string on linux terminal with c program.

At first, I’ll give you an introduction about foregroud and background colors, which are as following:

Foreground Colors		Background Colors
-----------------------------------------
Value		Color		Value	Color 
-----------------------------------------
30			Black		40		Black
31			Red			41		Red
32			Green		42		Green
33			Yellow      43      Yellow
34			Blue		44      Blue
35			Purple      45		Purple
36			Cyan        46      Cyan
37			White       47      White

I want to display a colorful string on the terminal, and the bash shell command as follows:

1
$ echo -e “\033[41;33mHello, this is a colorful characters string example.\033[0m”

shell colors

Now, I do it with c program colors.c, which content is:

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
43
44
45
46
47
48
49
50
#include <stdio.h> 

enum Foreground
{
FG_BLACK = 30,
FG_RED,
FG_GREEN,
FG_YELLOW,
FG_BLUE,
FG_PURPLE,
FG_CYAN,
FG_WHITE
};

enum Background
{
BG_BLACK = 40,
BG_RED,
BG_GREEN,
BG_YELLOW,
BG_BLUE,
BG_PURPLE,
BG_CYAN,
BG_WHITE
};

void set_color_str(const char *str, int fgcolor, int bgcolor);

int main()
{
enum Background backcolor = BG_YELLOW;
enum Foreground forecolor = FG_RED;

set_color_str("Here are the color words!", forecolor, backcolor);

return 0;
}

void set_color_str(const char *str, int fgcolor, int bgcolor)
{
if ((FG_BLACK > fgcolor) || (FG_WHITE < fgcolor)
|| (BG_BLACK > bgcolor) || (BG_WHITE < bgcolor))
{
printf("%s\n", str);
}
else
{
printf("\033[%d;%dm%s\n\033[0m", bgcolor, fgcolor, str);
}
}

Save it as colors.c and compile with gcc as following:

1
$ gcc colors.c -o colors

Then run it, and what happens?

1
$ ./colors

c colors

Yes, as you know, there is a colorful string printed on the terminal.