【发布时间】:2011-03-14 06:15:12
【问题描述】:
我正在制作一个需要彩色输出的简单应用程序。如何让我的输出像 emacs 和 bash 一样着色?
我不关心 Windows,因为我的应用程序仅适用于 UNIX 系统。
【问题讨论】:
我正在制作一个需要彩色输出的简单应用程序。如何让我的输出像 emacs 和 bash 一样着色?
我不关心 Windows,因为我的应用程序仅适用于 UNIX 系统。
【问题讨论】:
所有现代终端模拟器都使用 ANSI 转义码来显示颜色和其他内容。
不用理库,代码很简单。
更多信息是here。
C 中的示例:
#include <stdio.h>
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
int main (int argc, char const *argv[]) {
printf(ANSI_COLOR_RED "This text is RED!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_GREEN "This text is GREEN!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_YELLOW "This text is YELLOW!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_BLUE "This text is BLUE!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_MAGENTA "This text is MAGENTA!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_CYAN "This text is CYAN!" ANSI_COLOR_RESET "\n");
return 0;
}
【讨论】:
处理颜色序列可能会变得混乱,不同的系统可能会使用不同的颜色序列指示器。
我建议您尝试使用ncurses。除了颜色之外,ncurses 还可以通过控制台 UI 完成许多其他简洁的事情。
【讨论】:
您可以为每个功能分配一种颜色以使其更有用。
#define Color_Red "\33[0:31m\\]" // Color Start
#define Color_end "\33[0m\\]" // To flush out prev settings
#define LOG_RED(X) printf("%s %s %s",Color_Red,X,Color_end)
foo()
{
LOG_RED("This is in Red Color");
}
同样,您可以选择不同的颜色代码并使其更通用。
【讨论】:
您可以输出特殊颜色控制代码以获得彩色终端输出,这是how to print colors上的一个很好的资源。
例如:
printf("\033[22;34mHello, world!\033[0m"); // shows a blue hello world
编辑:我原来的一个使用提示颜色代码,它不起作用:(这个可以(我测试过)。
【讨论】:
edition.c: In function ‘int main(int, const char**)’: edition.c:4: error: unknown escape sequence '\]' edition.c:4: error: unknown escape sequence '\]' edition.c edition.c~ 只不过是一堆编译错误:(
22 更改为1 以粗体显示。
#include <stdio.h>
#define BLUE(string) "\x1b[34m" string "\x1b[0m"
#define RED(string) "\x1b[31m" string "\x1b[0m"
int main(void)
{
printf("this is " RED("red") "!\n");
// a somewhat more complex ...
printf("this is " BLUE("%s") "!\n","blue");
return 0;
}
阅读Wikipedia:
【讨论】:
因为您无法使用字符串格式打印字符。您也可以考虑添加类似这样的格式
#define PRINTC(c,f,s) printf ("\033[%dm" f "\033[0m", 30 + c, s)
f 的格式与printf 相同
PRINTC (4, "%s\n", "bar")
将打印blue bar
PRINTC (1, "%d", 'a')
将打印red 97
【讨论】:
如果你对整个程序使用相同的颜色,你可以定义printf()函数。
#include<stdio.h>
#define ah_red "\e[31m"
#define printf(X) printf(ah_red "%s",X);
#int main()
{
printf("Bangladesh");
printf("\n");
return 0;
}
【讨论】: