Linux 中的彩色控制台输出 [英] Colored console output in Linux

查看:55
本文介绍了Linux 中的彩色控制台输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 C 编程.第一个问题是选择在哪个平台上学习,我选择了Ubuntu.我找到了一个 GCC 编译器来编译我的项目,它对我来说很好用.我正在通过终端运行我编译的项目.但是当我想编写一个必须在彩色背景上显示文本的程序时,我明白终端并没有帮助我.实际上我正在学习为在 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

所以你可以这样写:

printf("x1b[31mThis is red textx1b[0m
");
printf("x1b[32mThis is green textx1b[0m
");

但此代码仅适用于兼容 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆