一:
在调试程序时,有时候要输出大量数据,如果让printf/fprintf改变输出数据的颜色,那观察数据就方便多了。 终端的字符颜色是用转义序列控制的,是文本模式下的系统显示功能,和具体的语言无关。 转义序列是以 ESC 开头,可以用 \033 完成相同的工作(ESC 的 ASCII 码用十进制表示就是 27, = 用八进制表示的 33)。 \033[显示方式;前景色;背景色m 显示方式:0(默认值)、1(高亮)、22(非粗体)、4(下划线)、24(非下划线)、5(闪烁)、25(非闪烁)、7(反显)、27(非反显) 前景色:30(黑色)、31(红色)、32(绿色)、 33(黄色)、34(蓝色)、35(洋红)、36(青色)、37(白色) 背景色:40(黑色)、41(红色)、42(绿色)、 43(黄色)、44(蓝色)、45(洋红)、46(青色)、47(白色) \033[0m 默认 \033[1;32;40m 绿色 033[1;31;40m 红色 printf( "\033[1;31;40m 输出红色字符 \033[0m" )
二:
如果是在windows平台下,这里面只需要用到Windows API的一个函数:SetConsoleTextAttribute
同样可以达到相同的目的
msdn上的说明如下:
BOOL SetConsoleTextAttribute(
HANDLE hConsoleOutput, // handle to screen buffer
WORD wAttributes // text and background colors
);
Parameters
hConsoleOutput
-
[in] Handle to a console screen buffer. The handle must have GENERIC_READ access.
wAttributes
-
[in] Specifies the foreground and background color attributes. Any combination of the following values can be specified: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces white text on a black background:
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
Return Values
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
To determine the current color attributes of a screen buffer, call the GetConsoleScreenBufferInfo function.
我们的使用如下:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
BOOL SetConsolColor(DWORD stdHandle, DWORD wAttributes=0x07UL)
{
HANDLE handle = GetStdHandle(stdHandle);
if(NULL == handle) {
return;
}
return SetConsoleTextAttribute(handle, wAttributes);
}
int _tmain(int argc, _TCHAR* argv[])
{
SetConsolColor(STD_OUTPUT_HANDLE, FOREGROUND_RED|BACKGROUND_GREEN);
printf("输出:绿底红字\n");
//SetConsolColor(STD_OUTPUT_HANDLE, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
SetConsolColor(STD_OUTPUT_HANDLE);
printf("默认:黑底白字\n");
return 0;
}
输出效果:

|