C 中的控制台着色无法正常工作

Console coloring in C not working correctly

我正在尝试用 C 编写一个简单的应用程序,我对 C 的概念还很陌生,所以如果这很简单,我深表歉意。我是 运行ning Windows 7 并且有一些类似的东西:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>

#define Green   "[0:32m"
#define Yellow  "[0:33m"
#define Reset   "[0m"
#define Log_info(X) printf("[Info] %s %s %s\n", Green,X,Reset)
#define Log_warn(X) printf("[Warning] %s %s %s\n",Yellow,X,Reset)
#define Seperator() printf("----------------------------------------------------\n")

void info(const char *message)
{  
    Log_info(message);
    Seperator();
}

void warn(const char *message)
{
    Log_warn(message);
    Seperator();
}

int main(int argc, char *argv[])
{
    warn("test the warning output for the console");
    info("test the information output for the console");
}

然而,当我尝试 运行 信息处理时,我得到以下信息:

[Warning] ←[0:33m test the warning output for the console ←[0m
----------------------------------------------------
[Info] ←[0:32m test the information output for the console ←[0m
----------------------------------------------------

我做错了什么,以至于它不是颜色协调输出,而是使用箭头?如何对信息进行颜色协调,黄色表示警告,绿色表示信息?

我主要从 Javascript (3[32m #<=Green) 和 Ruby (\e[32m #<=Green) 得到使用 [0:32m 的想法。

您没有使用正确的颜色代码。并且这些颜色代码仅适用于具有兼容终端的 Unix 系统。

由于您需要 C 和 Windows 特定的解决方案,我建议使用 Win32 API 中的 SetConsoleTextAttribute() 函数。您需要获取控制台的句柄,然后将其与适当的属性一起传递。

举个简单的例子:

/* Change console text color, then restore it back to normal. */
#include <stdio.h>
#include <windows.h>

int main() {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
    WORD saved_attributes;

    /* Save current attributes */
    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
    saved_attributes = consoleInfo.wAttributes;

    SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
    printf("This is some nice COLORFUL text, isn't it?");

    /* Restore original attributes */
    SetConsoleTextAttribute(hConsole, saved_attributes);
    printf("Back to normal");

    return 0;
}

有关可用属性的详细信息,请查看 here