JohnDoeYo
JohnDoeYo

Reputation: 209

Console coloring in C not working correctly

I'm attempting to write a simple application in C, I'm fairly new to the concept of C so I apologize if this is very simple. I'm running Windows 7 and have something along the lines of this:

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

#define Green   "\33[0:32m"
#define Yellow  "\33[0:33m"
#define Reset   "\33[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");
}

However when I attempt to run the information handling I get the following:

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

What am I doing wrong to the point where it is not color coordinating the output, and instead using the arrows? How can I color coordinate the information, yellow for warnings, green for information?

I got the idea of using \33[0:32m mostly from Javascript (\033[32m #<=Green) and Ruby (\e[32m #<=Green).

Upvotes: 3

Views: 1277

Answers (1)

syb0rg
syb0rg

Reputation: 8247

You aren't using the right color codes. And these color codes only work on Unix systems with compatible terminals.

Since you want a C and Windows specific solution, I'd recommend using the SetConsoleTextAttribute() function in the Win32 API. You'll need to grab a handle to the console, and then pass it with the appropriate attributes.

As a simple example:

/* 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;
}

For more info on the available attributes, look here.

Upvotes: 3

Related Questions