Colored console output in Linux

2020-07-22 09:33发布

问题:

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.

回答1:

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.



回答2:

The ncurses library does exactly what you are looking for. Using this library, you can choose to write any text, anywhere on the screen with any text/background color.

You can read more on it on Wikipedia. You can install it under ubuntu with:

$ sudo apt-get install libncurses5-dev


回答3:

If you want to start with GUI programming in Linux, you will probably have to look into one of GUI toolkits, which is a library to write GUI elements, widgets, etc.

One of these toolkints is Gtk, which you can start to learn via Gtk tutorial. Another option is Qt which is probably easier to use, but that is based on C++.

I'm afraid that Borland C++ Windows courses are pretty much unusable for Linux GUI programming.

Or, if you just to want a colored terminal text, look into this question: stdlib and colored output in C