不使用ncurses的C语言终端无关彩色打印
我正在编写一个输出测试结果的C程序,我希望它能以彩色打印出来,这样更容易扫描结果。我最初只是使用ANSI颜色代码(per),但一位代码评审员希望它更加独立于终端,并建议改用ncurses 使用ncurses的问题是,我的C程序输出的测试结果与bash脚本的其他测试结果混杂在一起。大概是这样的:不使用ncurses的C语言终端无关彩色打印,c,ncurses,C,Ncurses,我正在编写一个输出测试结果的C程序,我希望它能以彩色打印出来,这样更容易扫描结果。我最初只是使用ANSI颜色代码(per),但一位代码评审员希望它更加独立于终端,并建议改用ncurses 使用ncurses的问题是,我的C程序输出的测试结果与bash脚本的其他测试结果混杂在一起。大概是这样的: Test Name | Result ------------------------------ 1+1 == 2 | PASS <-- ou
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
...
测试名称|结果
------------------------------
1+1==2 | PASS猜猜看,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");
}
#包括
#包括
#包括
int main()
{
//首先,您需要初始化您的终端
int result=setupterm(0,1,0);
如果(结果!=0){
返回结果;
}
printf(“%-62.62s”,“1+1==2”);
//将颜色设置为绿色。您可以传递不同的函数
//如果你想,比如说,设置stderr颜色
TPUT(tparm(TIGETSR(“setaf”),颜色为绿色),1个putchar;
//将文本设置为粗体
tputs(tparm(tigetstr(“粗体”)),1,putchar;
//此文本将以绿色和粗体打印
printf(“PASS\n”);
//重置文本属性
tputs(tparm(tigetstr(“sgr0”)),1,putchar;
//现在,此文本将不再是绿色和粗体
printf(“完成”\n);
}
如您所见,您可以自由地将tput内容与常规printf输出进行混合和匹配。没有必要创建诅咒屏幕
有关tputs
、tparm
等的更多信息,请点击此处:
这里列出了您的终端可能具有的TIGETSR
功能:您可以直接使用terminfo/termcap接口,但如果您不喜欢ncurses api,您可能不会乐意这样做<依我看,code>ncurses
是一个相当合理的包装器。