Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colored console output in Linux

I just started learning programming in C. the first problem was to choose on which platform should I learn it, and I selected Ubuntu. I found a GCC compiler to compile my projects, and it worked fine for me. I was running my compiled projects through Terminal. But when I wanted to write a program which have to show a text on a colorful background, I understood that Terminal is not helping me. Actually I am learning from lessons written for programming on Windows, and they use there Borland C++ 5.2, but these lessons were written in 2007

So I am wondering, where I should run my compiled program in Ubuntu 10.10, to see the result properly? Actually I tried to transfer to Windows, but Ubuntu on my computer works much faster, and it is easier I think to work in Ubuntu rather than Windows.

like image 337
454b Avatar asked Sep 10 '25 19:09

454b


1 Answers

The simplest way to print color message without any toolkit is to use VT100 escape commands: http://www.termsys.demon.co.uk/vtansi.htm#colors

So you can write something like this:

printf("\x1b[31mThis is red text\x1b[0m\n");
printf("\x1b[32mThis is green text\x1b[0m\n");

But this code works only for VT100-compatible terminals (almost all terminals of the Unix-system). The best way is to check TERM environment variable before colorizing your output.

Disclaimer: if you want to write code capable with all terminal types then you should use ncurses-like library.

like image 150
Dmitry Poroh Avatar answered Sep 13 '25 10:09

Dmitry Poroh