![](/img/trans.png)
[英]How to set terminal background color on linux terminal without using ncurses?
[英]Terminal-agnostic color printing in C without using ncurses
我正在编写一个输出测试结果的 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 屏幕——我必须与其他 output 一起玩得很好。
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 output 混合搭配。 无需创建诅咒屏幕。
有关tputs
, tparm
等的更多信息: https://invisible-island.net/ncurses/man/curs_terminfo.3x.html
以下是您的终端可能具有哪些tigetstr
功能的列表: https://invisible-island.net/ncurses/man/terminfo.5.html#h3-Predefined-Capabilities
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.