我正在编写一个输出测试结果的 C 程序,我希望它以彩色打印它们,以便更容易扫描结果。我最初只使用 ANSI 颜色代码(根据 https://stackoverflow.com/a/23657072/4954731),但代码审阅者希望它更加独立于终端,并建议使用 ncurses。
使用ncurses的问题是我的C程序输出的测试结果与bash脚本的其他测试结果交织在一起。像这样的东西:
Test Name | Result
------------------------------
1+1 == 2 | PASS <-- outputted by a C executable
!(!true) == true | PASS <-- outputted by a bash script
0+0 == 0 | PASS <-- outputted by a C executable
...
所以我不能使用常规的 ncurses 屏幕 - 我必须与其他输出很好地配合。
bash 脚本使用
tput
和 setaf
进行彩色打印,但我不确定是否有办法在 C 上下文中使用这些工具,而无需直接查找和调用 tput
可执行文件...
有什么方法可以在不使用 ncurses 的情况下在 C 中进行与终端无关的彩色打印吗?
你猜怎么着,tput 实际上是底层 ncurses C 库的一部分!
这是使用 tput 打印彩色文本的示例。不要忘记使用
-lncurses
进行编译。
#include <stdio.h>
#include <curses.h>
#include <term.h>
int main()
{
// first you need to initialize your terminal
int result = setupterm(0, 1, 0);
if (result != 0) {
return result;
}
printf("%-62.62s ", "1+1 == 2");
// set color to green. You can pass a different function instead
// of putchar if you want to, say, set the stderr color
tputs(tparm(tigetstr("setaf"), COLOR_GREEN), 1, putchar);
// set text to bold
tputs(tparm(tigetstr("bold")), 1, putchar);
// this text will be printed as green and bold
printf("PASS\n");
// reset text attributes
tputs(tparm(tigetstr("sgr0")), 1, putchar);
// now this text won't be green and bold
printf("Done\n");
}
如您所见,您可以自由地将 tput 内容与常规 printf 输出混合搭配。无需创建诅咒屏幕。
有关
tputs
、tparm
等的更多信息:https://invisible-island.net/ncurses/man/curs_terminfo.3x.html
以下是您的终端可能具有的
tigetstr
功能列表:https://invisible-island.net/ncurses/man/terminfo.5.html#h3-Predefined-Capability