Linux中的彩色控制台输出 [英] Colored console output in Linux
问题描述
我刚刚开始学习C语言中的编程. 第一个问题是选择我应该在哪个平台上学习,然后我选择了Ubuntu. 我找到了一个GCC编译器来编译我的项目,它对我来说很好用.我正在通过Terminal运行我的编译项目. 但是当我想编写一个必须在彩色背景上显示文本的程序时,我了解到Terminal并不能帮助我.实际上,我是从为Windows编程编写的课程中学习,他们在那里使用Borland C ++ 5.2,但是这些课程是在2007年编写的.
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
所以我想知道应该在Ubuntu 10.10中运行我的编译程序的地方,以便正确看到结果吗? 实际上,我曾尝试过转移到Windows,但是我的计算机上的Ubuntu的运行速度要快得多,而且我认为在Ubuntu而不是Windows上运行更容易.
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.
推荐答案
在不使用任何工具箱的情况下打印彩色消息的最简单方法是使用VT100转义命令: http://www.termsys.demon.co.uk/vtansi.htm#colors
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");
但是此代码仅适用于VT100兼容终端(几乎是Unix系统的所有终端).最好的方法是在为输出着色之前检查TERM环境变量.
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.
免责声明:如果您想编写具有所有终端类型功能的代码,则应使用类似ncurses的库.
Disclaimer: if you want to write code capable with all terminal types then you should use ncurses-like library.
这篇关于Linux中的彩色控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!