我正在制作一个需要彩色输出的简单应用程序。如何让我的输出像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做许多其他整洁的事情。
你可以输出特殊的颜色控制代码来获得彩色终端输出,这里是how to print colors上的一个很好的资源。
例如:
printf("\033[22;34mHello, world!\033[0m"); // shows a blue hello world
编辑:我原来的一个使用提示颜色代码,这不起作用:(这一个(我测试过)。
您可以为每个功能指定一种颜色,以使其更有用。
#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");
}
同样,您可以选择不同的颜色代码,使其更通用。
如果对整个程序使用相同的颜色,则可以定义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;
}
因为您无法使用字符串格式打印字符。您还可以考虑添加这样的格式
#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
#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: