使用C / C ++,你怎么打印到标准输出的颜色,但只有当终端支持呢? [英] Using C/C++, how do you print to stdout in color, but only if the terminal supports it?

查看:274
本文介绍了使用C / C ++,你怎么打印到标准输出的颜色,但只有当终端支持呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有记录的事情节目 STDOUT

这些日志条目有一个相关的日志级别(调试,警告信息等),我想给用户上色这个输出的能力,取决于日志级别。

Those log entries have an associated "log level" (debug, warning, information, and so on) and I'd like to give the user the ability to color this output, depending on the log level.

什么是确定 STDOUT 被连在颜色能够在终端的方式吗?
而且我怎么能输出我的文字颜色呢?

What is the way of determining if STDOUT is attached to a terminal that is-color capable ? And how can I output my text with colors then ?

我在找只涉及C或C ++调用的解决方案。我猜诅咒(或的ncurses )的东西来缓解这个,但我想,以避免它的使用,以保持我的依赖关系到最低限度。

I'm looking for a solution that involves only C or C++ calls. I guess curses (or ncurses) has something to ease this, but I'd like to avoid its use to keep my dependencies to a minimum.

推荐答案

也许最简单的检查方法就是:

Probably the easiest way to check is simply:

isatty(fileno(STDOUT))

这将返回 1 如果你的标准输出被发送到任何类型的终端。在实践中,任何终端将支持或忽略VT100颜色codeS;检查的terminfo除非你期望能够输出一定果然非同一般的硬件终端是不必要的。 (其中大部分都没有几十年来取得。)

This will return 1 if your standard output is being sent to any sort of terminal. In practice, any terminal will either support or ignore VT100 color codes; examining terminfo is unnecessary unless you expect to be outputting to certain really unusual hardware terminals. (Most of which haven't been made in decades.)

要输出的颜色,使用(扩展)SGR序列:

To output colors, use the (extended) SGR sequence:

"\x1b[%dm"

其中,%d个是普遍支持的颜色以下值:

where %d is one of the following values for commonly supported colors:

0: reset colors/style
1: bold
4: underline
30 - 37: black, red, green, yellow, blue, magenta, cyan, and white text
40 - 47: black, red, green, yellow, blue, magenta, cyan, and white background

有更多的价值,但这些是最广泛支持的。再次,检查terminfo的是这些控制codeS主要是不必要的,因为每一个软件终端称职的支持(或忽略)它们。

There are more values, but these are the most widely supported ones. Again, examining terminfo is largely unnecessary for these control codes, as every software terminal worth its salt will support (or ignore) them.

如果您需要一次更改多个属性,你可以一次指定所有,用分号隔开。例如,下面的序列将烧焦大胆品红文字你的眼球绿色背景:

If you need to change multiple attributes at once, you can specify them all at once, separated by semicolons. For instance, the following sequence will sear your eyeballs with bold magenta text on a green background:

"\x1b[1;35;42m"

这篇关于使用C / C ++,你怎么打印到标准输出的颜色,但只有当终端支持呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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