微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

不使用 ncurses 的 C 中终端不可知的彩色打印

如何解决不使用 ncurses 的 C 中终端不可知的彩色打印

我正在编写一个输出测试结果的 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 脚本使用 tputsetaf 进行彩色打印,但我不确定是否有办法在 C 上下文中使用这些工具而无需直接查找和调用 {{1 }} 可执行文件...

有什么方法可以在不使用 ncurses 的情况下在 C 中进行终端不可知的彩色打印吗?

解决方法

猜猜看,tput 实际上是底层 ncurses C 库的一部分!

这是使用 tput 打印彩色文本的示例。不要忘记用 tput 编译。

-lncurses

如您所见,您可以自由地将 tput 内容与常规 printf 输出混合搭配。无需创建诅咒屏幕。

有关 #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),putchar); // set text to bold tputs(tparm(tigetstr("bold")),putchar); // this text will be printed as green and bold printf("PASS\n"); // reset text attributes tputs(tparm(tigetstr("sgr0")),putchar); // now this text won't be green and bold printf("Done\n"); } tputs 等的更多信息,请访问:https://invisible-island.net/ncurses/man/curs_terminfo.3x.html

以下是您的终端可能具有的 tparm 功能列表:https://invisible-island.net/ncurses/man/terminfo.5.html#h3-Predefined-Capabilities

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。